Consistent decimal semantics
waldemar at google.com
Mon Aug 25 17:25:23 PDT 2008
Brendan Eich wrote:
>> - Should decimal values behave as objects (pure library
>> implementation) or as primitives?
>> If they behave as objects, then we'd get into situations such as 3m !=
>> 3m in some cases and 3m == 3m in other cases. Also, -0m != 0m would
>> be necessary. This is clearly unworkable.
> What should be the result of (typeof 3m)?
"decimal". It should not be "object" because it doesn't behave like other objects!
>> 1. Always disallow it. For consistency you'd have to disallow ==
>> between Number and decimal as well.
> This was what Igor Bukanov and I were advocating last week.
>> 2. Allow it, converting to the wider type (Decimal128). There are a
>> couple design choices when doing the conversion:
>> 2a. Convert per the IEEE P754 spec: 5.1 turns into
>> 5.099999999999999644728632119949907m. This is how most programming
>> languages operate (C++, Java, Lisp, etc.) when converting among the
>> built-in floating point values (float -> double etc.).
> (I'm asking anyone who thinks so, as well as asking for your opinion:)
> Better than alternative 1? If so, why?
>> 2b. Convert the Number to a string and then to a Decimal: 5.1 turns
>> into 5.1m. As a special case, -0 would turn into -0m. This might
>> work, but I haven't thought through the implications of this one.
> Interesting idea.
Yes, I feel that either 2a or 2b would be better than alternative 1. Suppose you wanted to write a for-loop that works on both doubles and decimals:
This would presumably work:
for (i = low; i < high; i++)
But if you wanted to go up by two, this wouldn't:
for (i = low; i < high; i += 2)
Here (and in most other use cases) you're adding an integer, so rounding and such don't enter the picture. Similarly, generically checking whether
low < 0
would be annoying under option 1 if you didn't know whether low was a double or a decimal.
Not doing option 2a or 2b would make it hard to write generic methods, it would mean that you could use decimals to index arrays but not pass them to Array.prototype methods (unless we made those special as well), etc.
I'm off to Burning Man! I'll continue this discussion next week.
More information about the Es-discuss