-1

When I tried 0.1 + 0.2 in my JavaScript code, I'm getting the result 0.30000000000000004. I was expecting 0.3 as the result. Can anyone tell me why this is happening? Also, how can I work around this to get the result 0.3?

Sparky
  • 4,769
  • 8
  • 37
  • 52

1 Answers1

1

Edited with inputs from Alnitak

You have to specify the number of decimal places you want using the toFixed() method. If you want only one decimal place, then try

var result = (0.1 + 0.2).toFixed(1);

This expression returns a string which represents the floating point number rounded to 1 decimal place.

mridula
  • 3,203
  • 3
  • 32
  • 55
  • 1
    This converts it to string. – Praveen Kumar Purushothaman Apr 11 '13 at 11:11
  • really? But I have used this before, and didn't see it converting to string. – mridula Apr 11 '13 at 11:12
  • Please check it well... I checked again now... – Praveen Kumar Purushothaman Apr 11 '13 at 11:13
  • 2
    Even bigger crime is calling `parseFloat` on numbers – Esailija Apr 11 '13 at 11:13
  • You give `typeof parseFloat(0.1 + 0.2).toFixed(2)`, and it returns `"string"` – Praveen Kumar Purushothaman Apr 11 '13 at 11:14
  • @mridula Thanks for you answer. I'm not a purist, so I'll take your answer. Besides, no one else is having a better solution anyway! – Sparky Apr 11 '13 at 11:22
  • 1
    @Sparky that's because there is no "better solution". It's just how numbers work in JS. But IMHO this answer is still not worthy of acceptance because it's wrong on two counts. – Alnitak Apr 11 '13 at 11:28
  • 1. it returns a `string` (that's actually OK, but it's a shame the OP didn't know that) 2. it converts `0.1 + 0.2` (i.e. `0.3`) _into_ a string so it can then be passed to `parseFloat`, which then turns it _back_ into a `Number` on which `.toFixed()` is invoked. The right answer should be "you cannot represent 0.3 as an exact number in a numeric variable, but if you call `(0.3).toFixed(n)` you can obtain a string _representing_ that number rounded to the desired number of decimal places." – Alnitak Apr 11 '13 at 11:48
  • 1
    @Alnitak, I understand that. Thanks. But this works for me, whether its a solution or a workaround. So I accepted the answer, hoping that it would help someone like me. No offense meant. – Sparky Apr 11 '13 at 12:11