Last Updated: February 25, 2016
·
1.227K
· zigotica

round percentage to a mask

You need a percentage to be rounded not to 0/100 but a more accurate value. For instance, given

var n = 0.76,
    r = Math.round(n);

r will be 1 since it is closer to 1 than 0. If we want to have smaller round values, like 0.05 increments, we will need to use a mask and modify the formula a bit:

var n = 0.76,
    mask = 0.05,
    r = mask * Math.round( n / mask);

r will be 0.75 now. The obvious step if we want the final percentage, we multiply by 100 factor and add the symbol:

var n = 0.76,
    mask = 0.05,
    r = 100 * mask * Math.round( n / mask) + "%";

r will be 75% now.

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside