1

Round number to specific decimal places

Function JavaScript 1 revisions 49 6 months ago 6 months ago
function round(number, precision) {
    var pair = (number + 'e').split('e')
    var value = Math.round(pair[0] + 'e' + (+pair[1] + precision))
    pair = (value + 'e').split('e')
    return +(pair[0] + 'e' + (+pair[1] - precision))
}

This function rounds numbers a given decimal place only if necessary.

round(1.005, 2);                     // 1.01
round(1.0005, 2);                    // 1
round(112421421421.124214214124, 5); // 112421421421.12422
  • It will not return things like 1.00 but rather just 1
  • Supposedly it should not fail on things like 0.0000005 (floating point inaccuracy)
  • It does handle any large numbers.