4 ms·
You can "cast" a JavaScript number to int: nr = nr | 0 Then use the cents instead of decimal dollars. But it might be a good idea to use a bigint lib. And
by z3t4 9y ago
You can "cast" a JavaScript number to int:
nr = nr | 0
Then use the cents instead of decimal dollars.
But it might be a good idea to use a bigint lib.
And remember different countries might have different rounding rules.
- jessaustin 9y ago...and different industries in a given country, and different firms in a given industry, and different departments in a given firm, and different contracts used by a given department...
- zaxomi 9y agoUsing | will cast it to a 32 bit integer! 2147483648 | 0 = -2147483648 -2147483649 | 0 = 2147483647 4294967296 | 0 = 0 -4294967296 | 0 = 0 6442450944 | 0 = -2147483648
- dchest 9y agoJavaScript numbers can hold integers without losing precision up to Number.MAX_SAFE_INTEGER (9007199254740991, or 2⁵³-1), can be checked with Number.isSafeInteger(). Bitwise arithmetics, though, works on 32-bit numbers, so "casting" with | 0 will actually result in converting the number to 32-bit signed integer: 2**53-1 | 0 = -1 2**53-2 | 0 = -2 Which is modular arithmetic: (2**53-2) % 2**32 = 4294967294 2**53-2 >>> 0 = 4294967294 ( >>> 0 makes unsigned, 4294967294 | 0 = -2)
- itslennysfault 9y agoMy code review comment on this would be... Don't be "clever". Use parseInt or parseFloat.
- tobr 9y agoThat’s a terrible idea: parseInt(0.000001) // 0 parseInt(0.0000001) // 1
- jannes 9y agoFor anyone who is wondering why: parseInt() only accepts strings as input. So JavaScript calls .toString() on the number before passing it as an argument. (0.000001).toString() // "0.000001" (0.0000001).toString() // "1e-7" By the way, TypeScript or Flow would have caught this error during compile time.
- jannes 9y agoparseInt() and parseFloat() are made for strings, not for numbers. I think you are looking for one of these: Math.round() Math.ceil() Math.floor()