Division of float numbers in JavaScript

梦想与她 提交于 2020-01-04 05:06:07

问题


I'm trying to divide screenwidth by a variable in order to draw equally spaced UI parts in webview.

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.

Is there any nice workaround for this problem?


回答1:


You can specify the precision of the division:

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



回答2:


The best you can do is get as close as possible:

(100 / 3).toFixed(2)



回答3:


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.




回答4:


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.




回答5:


100 * (1/3) will return 33.33333333333333.

Note:

1/3 * 100 returns 33.33333333333333

but

100 * 1/3 returns 33.333333333333336

So use parenthesis to be safe.



来源:https://stackoverflow.com/questions/17902815/division-of-float-numbers-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!