7

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?

mmrn
  • 249
  • 2
  • 8
  • 18
  • 1
    possible duplicate of [Is JavaScript's Floating-Point Math Broken?](http://stackoverflow.com/questions/588004/is-javascripts-floating-point-math-broken) –  Jul 27 '13 at 22:02

5 Answers5

15

You can specify the precision of the division:

var width = (100 / 3).toPrecision(3);
Derick Leony
  • 421
  • 2
  • 7
7

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

(100 / 3).toFixed(2)
Jivings
  • 22,834
  • 6
  • 60
  • 101
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.

Patricia Shanahan
  • 25,849
  • 4
  • 38
  • 75
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.

s_curry_s
  • 3,332
  • 9
  • 32
  • 47
-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.

  • 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. – zypA13510 Nov 02 '20 at 02:30