Javascript parsefloat 错误的减法

Javascript parsefloat bad subtraction

我要减去两个浮点数,但我得到 999998.7799999999 为什么?实际结果是 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));

您的问题与浮点精度有关。 你可以找到解释here.

您想要的结果只是 Javascript 生成的结果 (read more about floating point operations in Javascript) 的四舍五入版本。您可以自己舍入结果以获得您想要的格式:

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);

结果是由于浮点精度,Python文档有很好的解释。 https://docs.python.org/2/tutorial/floatingpoint.html

您可以使用 toFixed(2),因为您只使用两位数字:

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.

片段:

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);