JavaScript 中浮点数的除法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17902815/
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
Division of float numbers in JavaScript
提问by mmrn
I'm trying to divide screenwidth by a variable in order to draw equally spaced UI parts in webview.
我正在尝试将屏幕宽度除以一个变量,以便在 webview 中绘制等距的 UI 部分。
However, when the variable is 3, 100 / 3 results 33.3333333333333336 in JavaScript, and the third part cannot be drawn as intended because the sum of the quotients is bigger than 100%, I gusss.
但是,当变量为 3 时,100 / 3 在 JavaScript 中的结果为 33.3333333333333336,第三部分无法按预期绘制,因为商数之和大于 100%,我猜。
Is there any nice workaround for this problem?
这个问题有什么好的解决方法吗?
回答by Derick Leony
You can specify the precision of the division:
您可以指定除法的精度:
var width = (100 / 3).toPrecision(3);
回答by Jivings
The best you can do is get as close as possible:
你能做的最好的事情就是尽可能接近:
(100 / 3).toFixed(2)
回答by Gorkem Yurtseven
You can do
你可以做
Math.floor(100/3);
which would always round the decimal to the smaller closest integer, so in your case it would round it to 33.
它总是将小数四舍五入为最接近的较小整数,因此在您的情况下,它将四舍五入为 33。
回答by Patricia Shanahan
Get the width as close as you can for two of the three slices. Subtract the sum of their actual widths in pixels from the target width in pixels to get the width of the third slice. It may be one or two pixels wider or narrower than the other slices, but that will not be visible for any reasonable screen resolution.
为三个切片中的两个获取尽可能接近的宽度。从以像素为单位的目标宽度减去它们以像素为单位的实际宽度的总和,以获得第三个切片的宽度。它可能比其他切片宽或窄一或两个像素,但对于任何合理的屏幕分辨率,这都将不可见。
回答by Stanley Novak
100 * (1/3) will return 33.33333333333333.
100 * (1/3) 将返回 33.33333333333333。
Note:
笔记:
1/3 * 100 returns 33.33333333333333
1/3 * 100 返回 33.33333333333333
but
但
100 * 1/3 returns 33.333333333333336
100 * 1/3 返回 33.333333333333336
So use parenthesis to be safe.
所以使用括号是安全的。