Division of float numbers in JavaScript

24,535

Solution 1

You can specify the precision of the division:

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

Solution 2

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

(100 / 3).toFixed(2)
Share:
24,535
mmrn
Author by

mmrn

Updated on August 20, 2020

Comments

  • mmrn
    mmrn over 3 years

    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?