4 ms·
Try adding 1.3 + 1.1 and tell me JavaScript isn't broken. Hint: The result is isn't 2.4, it's 2.4000000000000004. Unfortunately that's something TypeScript do
by niieani 10y ago
Try adding 1.3 + 1.1 and tell me JavaScript isn't broken.
Hint: The result is isn't 2.4, it's 2.4000000000000004.
Unfortunately that's something TypeScript doesn't tackle, but you can use external libraries for floats, where you work on floats as... strings.
- dvlsg 10y agoThat's arguably a problem in almost every language that follows the IEEE 754 standard. It doesn't make much sense to pin that problem solely on Javascript.
- qwertyuiop924 10y agoJS does that... And so does C, and just about every other language out there.
- keithnz 10y agowhen you work with floats, never expect anything to exactly equal a value, ie, it should be banned to use <float> === <constant> . That is universal across languages, for exact representations often languages provide another type. But floating point is popular because CPUs can natively work with them.
- Roboprog 10y agoFor financial work, you want to use a fixed precision or binary coded decimal library, such as java's BigDecimal. You knew that, but I'm just spelling it out for others.
- qwertyuiop924 10y ago...Or you could use Scheme, where we have precise numbers (fractions)
- h1d 10y agoIs that your only complaint about JS?
- Roboprog 10y agoWell, here's one way around that, at least on the server: https://github.com/roboprog/nashorn_play/blob/master/script/np_script/src/js/java_user.js https://github.com/roboprog/nashorn_play/blob/master/script/...