JavaScript floating point separation

I am trying to split the width of the screen into a variable in order to draw evenly distributed parts of the user interface in webview.

However, when the variable is 3, 100/3 the result is 33.3333333333333336 in JavaScript, and the third part cannot be drawn as intended, because the sum of the coefficients is more than 100%, I am gusss.

Is there any good workaround for this problem?

+3
source share
5 answers

You can specify the division accuracy:

var width = (100 / 3).toPrecision(3); 
+9
source

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

 (100 / 3).toFixed(2) 
+4
source

You can do

 Math.floor(100/3); 

which will always round the decimal to the smallest nearest integer, so in your case it will be rounded to 33.

+1
source

Get the width as close as possible to two of the three slices. Subtract the sum of their actual width 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 smaller than other slices, but this will not be visible for any reasonable screen resolution.

0
source

100 * (1/3) will return 33.3333333333333333.

Note:

1/3 * 100 returns 33.33333333333333

but

100 * 1/3 returns 33.333333333333336

Therefore, use parentheses to ensure safety.

0
source

Source: https://habr.com/ru/post/1258690/


All Articles