Last Updated: February 25, 2016
·
892
· 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.