0

I am having trouble with multiplying my numbers and getting not correct value.

I have numbers 1,2,3,6,12 and 2.95,3.95,6.95,15,95

but when I multiply my number 3 with 2.95 using 2.95 * parseInt('3') it returns 8.850000000000001

and when I multiply 12 with 15.95 it returns 179.3999999999998.

I dont want this too long zeros and this kind of value .8500000000001

its also returns some of those numbers when they multiply.

how to get rid of this? how can I get complete value like 12 * 15.95 should give 179.40

  • For JavaScript you can utilize `Math.round()` to do this. Take a look here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round @Juhana No it's not, you didn't even read the question did you. – Spencer Wieczorek Jul 03 '14 at 14:51
  • Although this question asks how to get rid of the effects rather than why this happens, it should still be marked as a duplicate of "Is floating point math broken?" because the answer is provided there: http://stackoverflow.com/a/8633598/1248365 – Adi Inbar Jul 03 '14 at 19:55

2 Answers2

1

You want to use .toFixed() (keep in mind this will return a string):

var myString = (12 * 15.95).toFixed(2);
//myString = "191.40"
nicael
  • 18,550
  • 13
  • 57
  • 90
Jack
  • 8,851
  • 3
  • 21
  • 26
  • 2
    That's literally it. But here you go. http://jsfiddle.net/83BZZ/ – Jack Jul 03 '14 at 14:56
  • Well this is great, literally awesome :D –  Jul 03 '14 at 14:58
  • Remember to keep your significant digits in check. If you're multiplying 12.95 by 12.95, for example, you'll want to use `.toFixed(4)` instead of `.toFixed(2)` – River Tam Jul 03 '14 at 15:07
  • Expanding on @RiverTam you're probably not going to want to use `.toFixed()` until you are outputting the final result for display. – Jack Jul 03 '14 at 15:08
-1

Instead of Jack's answer, which is also valid, you can just use Math.round10

To round to 2 decimal places, use Math.round10(x, -2)

For example:

var answer = Math.round10(12 * 15.95, -2);

This differs from Jack's answer in that it gives you the value as a number rather than as a string, saving a couple of keystrokes.

River Tam
  • 3,096
  • 4
  • 31
  • 51