29

I have:

var a =  0.0532;
var b =  a * 100;

b should be returning 5.32 but instead it's returning 5.319999999999999. How do I fix this?

JSFiddle here: http://jsfiddle.net/9f2K8/

Jee Mok
  • 6,157
  • 8
  • 47
  • 80
user3213420
  • 351
  • 1
  • 5
  • 11
  • Here is a solution: ```JavaScript function moveComma(val, moveCommaByInput) { if (val || typeof val === 'number') { const valueNumber = Number(val); const moveCommaBy = moveCommaByInput || 0; if (isNaN(valueNumber)) { return null; } else { return Number(`${valueNumber}e${moveCommaBy}`); } } return null; } ``` – Jacek Koziol Oct 08 '21 at 11:40

2 Answers2

19

you should use .toFixed()

FIDDLE

var a =  0.0532;
var b =  a * 100;
b.toFixed(2);     //specify number of decimals to be displayed
yashhy
  • 2,856
  • 5
  • 31
  • 57
  • I don't know if I'd make the assumption `2` is safe as an argument for `.toFixed`. What if `a = 0.53245239934`? or `b = 10`? – Mulan Jan 31 '14 at 05:15
  • @naomik if `a = 0.53245239934` will return `0.53` and `10.00` for b – yashhy Jan 31 '14 at 05:20
  • I'm just saying you might not want to make the assumption that `2` is an acceptable precision just because you wouldn't lose data in this specific scenario. – Mulan Jan 31 '14 at 05:21
  • 1
    Number.prototype.toFixed is a function designed to format a number. It returns a string. If you need a number not a string, have a look at this answer https://stackoverflow.com/a/29494612/228770 – Ed Spencer Feb 13 '18 at 14:39
14

This is not an error.

Javascript is trying to represent 5.32 with as much precision as possible. Since computers don't have infinite precision, it picks the closest number it can: 5.319999999999999.

If your problem lies with numerical operations, you should be able to add/multiply/etc these numbers without problem. They so close to the intended number that results will be within a negligible margin of error.

If your problem lies with comparing numbers, the common approach is to ditch == and instead compare using a defined margin of error. For example:

// Two previously obtained instances of the "same" number:
a = 5.32
b = 5.319999999999999

// Don't do this:
if (a == b) {}

// Do this instead (hide it in a function):
margin = 0.000001
if (Math.abs(a - b) < margin) {}

If your problem is visual, you can use toFixed() to create a rounded human-readable string:

number = 123.4567
number.toFixed(2)
> '123.46'
salezica
  • 74,081
  • 25
  • 105
  • 166