Division of float numbers in JavaScript
Asked Answered
L

5

8

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?

Labored answered 27/7, 2013 at 21:53 Comment(1)
possible duplicate of Is JavaScript's Floating-Point Math Broken?Dowsabel
L
16

You can specify the precision of the division:

var width = (100 / 3).toPrecision(3);
Lymn answered 27/7, 2013 at 21:57 Comment(0)
M
8

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

(100 / 3).toFixed(2)
Merkle answered 27/7, 2013 at 21:59 Comment(0)
D
1

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.

Dramamine answered 28/7, 2013 at 15:2 Comment(0)
R
0

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.

Rosemarierosemary answered 27/7, 2013 at 21:56 Comment(1)
Then there will be a 1% loss in screen real estate :PMerkle
M
-2

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.

Myongmyopia answered 19/8, 2015 at 21:31 Comment(1)
100*(1/27) returns 3.7037037037037033, 1/27*100 returns 3.7037037037037033, 100*1/27 returns 3.7037037037037037. So it's not an issue of parenthesis.Mitinger

© 2022 - 2024 — McMap. All rights reserved.