简体   繁体   English

JavaScript中浮点数的划分

[英]Division of float numbers in JavaScript

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时,JavaScript中的100/3结果为33.3333333333333336,而第三部分无法按预期绘制,因为商的总和大于100%,我说。

Is there any nice workaround for this problem? 这个问题有什么好的解决方法吗?

您可以指定除法的精度:

var width = (100 / 3).toPrecision(3);

你能做的最好的就是尽可能接近:

(100 / 3).toFixed(2)

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。

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. 它可能比其他切片更宽或更窄一个或两个像素,但对于任何合理的屏幕分辨率都不可见。

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. 所以使用括号是安全的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM