4 ms·
Don't miss the link to React "workaround" (http://stackoverflow.com/a/20796543/311196 http://stackoverflow.com/a/20796543/311196): This is actually a feature o
by dchest 12y ago
Don't miss the link to React "workaround" (http://stackoverflow.com/a/20796543/311196 http://stackoverflow.com/a/20796543/311196):
This is actually a feature of React: your UI is guaranteed to always be in sync with your underlying data!
...
It sounds like you want to be able to show either an exact °C temperature or an exact °F temperature, so the best approach here seems to be to store that as well. Otherwise, you're feigning more precision than you actually have.
- zwily 12y agoI think that given the fp imprecision of javascript, just storing either C or F is the wrong thing to do, and the "workaround" is actually correct.
- lhorie 12y agoI came to the same conclusion when I implemented it in Mithril ( http://jsfiddle.net/qQ59s/ http://jsfiddle.net/qQ59s/ ) The way I thought about it is that a temperature conversion model entity needs 4 API points (get as °C, get as °F, set as °C, set as °F), and you want the canonical precision to be bound to the latest modified unit of temperature. The "mathematically correct" approach would get pretty complicated with a fraction library and value objects, but given that the output of the conversion cannot always be expressed as a decimal on the UI in the first place, and that the weight of the "correct" solution far outweights adding a second storage variable, we can make an engineering decision to simplify the implementation while staying correct enough for the purposes of the example. In fact, the vanilla JS implicitly does the exact same thing by storing the canonical precision in the last modified field's `value` attribute. Typically, you'd want to store the result of a computation when setting anyways, since re-computing them on every read can be expensive. In code, this simply means that you store the latest modified value as-is, and store the imprecise computed value for the other unit of temperature: var Temperature = function() { this.setCelsius = function(c) { this.celsius = c this.fahrenheit = 9/5 * c + 32 } this.setFahrenheit = function(f) { this.fahrenheit = f this.celsius = 5/9 * (f - 32) } } var t = new Temperature t.setFahrenheit(2) //we want 2°F to mean 2°F, not 1.999... As a related note, it's kinda curious that some of the implementations end up having slightly different semantics, specifically in order to fit into their frameworks (and an implicit desire for terseness), and sacrifice code quality (in terms of logic encapsulation, computational cost profile, etc.) to achieve that end.
- Joeri 12y agoYou can get a more sane and stable mathematical behavior by the simple mechanism of rounding to two digits: http://jsfiddle.net/qQ59s/1/ http://jsfiddle.net/qQ59s/1/