JavaScript 中的 parseDecimal ?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10984748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
parseDecimal in JavaScript?
提问by jeffery_the_wind
I have some JS calculations going on. Since floating point arithmetic often uses close approximations to numbers instead of exact values, if you round these floating point number to fixed precision, you often get slight differences. When you are dealing with dollars, people don't like these slight differences.
我正在进行一些 JS 计算。由于浮点运算通常使用数字的近似值而不是精确值,如果将这些浮点数四舍五入到固定精度,通常会得到细微的差异。当你处理美元时,人们不喜欢这些细微的差别。
My problem is outlined in this jsfiddle: http://jsfiddle.net/rGP8Q/.
这个 jsfiddle 概述了我的问题:http: //jsfiddle.net/rGP8Q/。
Does anyone know how I can do math operations (multiplication and addition) without introducing these rounding errors coming from the floating point approximations?
有谁知道我如何在不引入这些来自浮点近似值的舍入误差的情况下进行数学运算(乘法和加法)?
EDIT
编辑
I found this other post which brings up the same problem, and confirms that JS does not have a built in decimal data type: How to deal with floating point number precision in JavaScript?.
我发现另一个帖子提出了同样的问题,并确认 JS 没有内置的十进制数据类型:如何处理 JavaScript 中的浮点数精度?.
you can see if you JS terminal that
你可以看看你的 JS 终端
626.175.toFixed(2) == 626.17
626.185.toFixed(2) == 626.18
626.195.toFixed(2) == 626.20
which is inconsistent. We need a true decimal data type.
这是不一致的。我们需要一个真正的十进制数据类型。
回答by Niet the Dark Absol
Yes. Always, ALWAYS deal in units of the smallest denomination, and ONLY divide by 100 at the end, for display purposes only.
是的。始终以最小面额的单位进行交易,最后仅除以 100,仅用于显示目的。