4 ms·
But there's no way to do so in JavaScript unless you implement a numeric type by hand, something that Dinero does not do. In JavaScript every number is a IEEE7
by partycoder 8y ago
But there's no way to do so in JavaScript unless you implement a numeric type by hand, something that Dinero does not do.
In JavaScript every number is a IEEE754 floating point number, and removing decimal places will not change its representation in memory or its limitations.
The only situation when a JavaScript Number type is treated as an integer is a vendor specific optimization for small integers (e.g: Smi in v8).
You can still run into issues such as absorption problems if dealing with only "integers". e.g:
> 1e16 -1
10000000000000000 // wrong
> 1e16 -2
9999999999999998
> 1e16 -3
9999999999999996 // wrong
> 1e16 -4
9999999999999996
> 1e16 -5
9999999999999996 // wrong
> 1e16 -6
9999999999999994
> 1e16 -7
9999999999999992 // wrong
But this is just the beginning.
- dchest 8y agoBut there's no way to do so in JavaScript unless you implement a numeric type by hand This is not true: with 64-bit floating-point numbers, calculations on numbers in a range from Number.MIN_SAFE_INTEGER (2^53-1) to Number.MAX_SAFE_INTEGER (-2^53-1) are safe to do. If you go outside this range, the numbers are no longer exact, so you'll have to check for overflow, but it's the same when you use native machine integer types (e.g. uint64) in most languages that have them. The only situation when a JavaScript Number type is treated as an integer is a vendor specific optimization for small integers (e.g: Smi in v8). A number is integer if it doesn't have a fractional component regardless of how it's represented by a computer. There are also operations in JavaScript that treat their inputs as 32-bit integers (numbers are taken modulo 2^32), such as bitwise operations and Math.imul. But if you don't use them, integers can be as large or as small as described above.
- partycoder 8y agoSome numbers do not have an exact representation in IEEE754. This leads to problems such as: > 1.03 - 0.42 0.6100000000000001
- deleted 8y ago[deleted]
- dchest 8y agoThese are not integers! Integers are exactly represented from -2^53-1 to 2^53-1.
- partycoder 8y agoYou claim that as long as numbers fit in a double precision IEEE754 floating point number significand, which is what JS implements, you are safe. Fine. But what happens after successive operations? the risk increases. Is this a good idea when dealing with currency? No. Does this library warn you about those cases or throw an error? no. Does this library provide unit tests for those cases? no.
- dchest 8y agoI agree that this library doesn't looks good — a proper implementation would use a better precision (e.g. 1/10000 of a currency unit) rather than "cents" (1/100), and of course, check ranges and the absence of fractions (Number.isSafeInteger).