简体   繁体   中英

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.

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?

您可以指定除法的精度:

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.

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.

Note:

1/3 * 100 returns 33.33333333333333

but

100 * 1/3 returns 33.333333333333336

So use parenthesis to be safe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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