1

I am going to subtract two floats but I get 999998.7799999999 why ? It real result is 999998.78

Money1="2,000,001.44 $";
Money2="1,000,002.66 $"
Money1= Number(Money1.replace(/[^0-9\.]+/g,""));
Money2= Number(Money2.replace(/[^0-9\.]+/g,""));
console.log(parseFloat(Money1)-parseFloat(Money2));
Daniel Kobe
  • 9,376
  • 15
  • 62
  • 109
Somomo1q
  • 655
  • 2
  • 10
  • 19

4 Answers4

2

You can use toFixed(2) because you are working only with two digits:

toFixed() returns a string representation of numObj that does not use exponential notation and has exactly digits digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length. If numObj is greater than 1e+21, this method simply calls Number.prototype.toString() and returns a string in exponential notation.

The snippet:

Money1="2,000,001.44 $";
Money2="1,000,002.66 $"
Money1= Number(Money1.replace(/[^0-9\.]+/g,""));
Money2= Number(Money2.replace(/[^0-9\.]+/g,""));
result = (Money1 - Money2).toFixed(2);
console.log(result);
gaetanoM
  • 41,594
  • 6
  • 42
  • 61
1

Your Problem is related to floating point precision. You can find a explanation here.

Community
  • 1
  • 1
alexloehr
  • 1,773
  • 1
  • 20
  • 18
1

The result you want is just a rounded version of the what Javascript is producing (read more about floating point operations in Javascript). You can round the result yourself to get the formatting you desire:

Money1="2,000,001.44 $";
Money2="1,000,002.66 $"
Money1= Number(Money1.replace(/[^0-9\.]+/g,""));
Money2= Number(Money2.replace(/[^0-9\.]+/g,""));
Rounded = Math.round((parseFloat(Money1)-parseFloat(Money2)) * 100) / 100;
console.log(Rounded);
Community
  • 1
  • 1
Rob M.
  • 35,491
  • 6
  • 51
  • 50
1

The result is due to floating point precision, the Python docs have a great explanation. https://docs.python.org/2/tutorial/floatingpoint.html

Daniel Kobe
  • 9,376
  • 15
  • 62
  • 109