在 JavaScript 中限制浮点精度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19980692/
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
Restrict Float Precision in JavaScript
提问by Sai Avinash
I'm working on a function in JavaScript. I take two variables x and y.
我正在处理 JavaScript 中的一个函数。我取两个变量 x 和 y。
I need to divide two variables and display result on the screen:
我需要划分两个变量并在屏幕上显示结果:
x=9; y=110;
x/y;
then I'm getting the result as :
然后我得到的结果是:
0.08181818181818181
0.08181818181818181
I need to do it with using some thing like BigDecimal.js
that I found in another post.
我需要使用BigDecimal.js
我在另一篇文章中找到的类似东西来做到这一点。
I want that result was shown as:
我希望结果显示为:
0.081
0.081
回答by kajojeq
Try this it is rounding to 3 numbers after coma:
试试这个,它在昏迷后四舍五入为 3 个数字:
(x/y).toFixed(3);
Now your result will be a string. If you need it to be float just do:
现在你的结果将是一个字符串。如果您需要它是浮动的,请执行以下操作:
parseFloat((x/y).toFixed(3));
回答by Dallas
You can do this
你可以这样做
Math.round(num * 1000) / 1000
This will round it correctly. If you wish to just truncate rather than actually round, you can use floor()
instead of round()
这将正确舍入它。如果您只想截断而不是实际舍入,则可以使用floor()
代替round()
回答by Joren
Use this to round 0.818181... to 0.81:
使用它来将 0.818181... 舍入到 0.81:
x = 9/110;
Math.floor(x * 1000) / 1000;
回答by Wallace Maxters
Try this
试试这个
var num = x/y;
parseFloat((Math.round(num * 100) / 100).toPrecision(3))
回答by Sergio Belevskij
if i'm use the simple expression, result may be unexpected:
如果我使用简单的表达式,结果可能会出乎意料:
const fraction = (value) => {
return value - Math.floor(value);
}
fraction(1 / 3);
=> 0.333333333333 // is Right
fraction(22 / 3);
=> 0.33333333333333304 // is Unexpected
So, my robust expression is:
所以,我健壮的表达是:
const fraction = (value) => {
return parseFloat(value.toString().replace(/^\d+$/, '0').replace(/^.+?(?=\.)/, ''))
}
fraction(22 / 3);
=> 0.333333333333333
fraction(1111)
=> 0
fraction(.122211)
=> 0.122211
fraction(11111.122211)
=> 0.122211
fraction(11111.12)
=> 0.12
fraction(11111.11112)
=> 0.11112