for example in javascript addition of 1 + 0.59 is 1.5899999999999999 but I want output of 1.59 which looks right to me.
Asked
Active
Viewed 1,368 times
-1
-
1please check the following doc https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round – Michael Meyer Oct 11 '17 at 06:59
-
1https://stackoverflow.com/questions/15762768/javascript-math-round-to-two-decimal-places possible duplicate – Salman Oct 11 '17 at 06:59
-
The nearest double to 0.59 is 0.58999999999999996891375531049561686813831329345703125. The rot sets in there. Lots of ways of dealing with this in the duplicate. – Bathsheba Oct 11 '17 at 07:03
-
1If you need this for currency operations I strongly recommend using a special decimal type or slice your whole numbers into arrays and then do the math on those array items. This could also help: http://floating-point-gui.de/languages/javascript/ – Nicolae Olariu Oct 11 '17 at 07:04
-
@NicolaeOlariu, yes, it's a good advice. – Mihai Alexandru-Ionut Oct 11 '17 at 07:09
1 Answers
0
Use .toFixed()
to round your number.
alert((1+0.58999999999).toFixed(2));

Justinas
- 41,402
- 5
- 66
- 96
-
1`22k` reputation you know that question was a duplicate or not.Don't answer the exact duplicate question.I m not downvoter – prasanth Oct 11 '17 at 07:02
-
I don't understand the downvote. This seems like good advice to me. Although the answerer could expand more on the reasons. – Bathsheba Oct 11 '17 at 07:06