Round Numbers Accurately to Specified Place Value with Javascript

This function rounds numbers to a specified accuracy. There are several ways to round in Javascript. Some rounding methods are faster than others, and some are more accurate, in terms of rounding errors, than others.

All four of these Javascript rounding functions are accurate to 15 decimal places, after which there is a small variation in the rounding accuracy.

To use any of the functions below call like this,

Javascript: round(3.14159265358979323846, 4);
Result: 3.1416

Method #1

function round(value, decimals) {
    return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}

// ~67 avg milliseconds to iterating 10,000 times.

Javascript: round(3.14159265358979323846, 20);
Result: 3.14159265358979311600 // rounding error by 0.00000000000000012246

Method #2

function round2(value, decimals) {
    var accuracy = Math.pow(10, decimals || 0);
    return Math.round(value * accuracy) / accuracy;
}

// ~60 avg milliseconds to iterating 10,000 times.

Javascript: round(3.14159265358979323846, 20);
Result: 3.14159265358979356009 // rounding error by 0.00000000000000032163

Method #3 NOTE: this method returns a string

function round3(value, decimals) {
    var accuracy = decimals || 0;
    return parseFloat(parseFloat(value)).toFixed(accuracy);
}

// ~58 avg milliseconds to iterating 10,000 times.

Javascript: round(3.14159265358979323846, 20);
Result: 3.14159265358979311600 // rounding error by 0.00000000000000012246

Method #4

function round4(value, decimals) {
  return Number.parseFloat(value).toPrecision(decimals);
}

// ~61 avg milliseconds to iterating 10,000 times.

Javascript: round(3.14159265358979323846, 20);
Result: 3.14159265358979356009 // rounding error by 0.00000000000000032163

 

Copyright © Lage.us Website Development | Disclaimer | Privacy Policy | Terms of Use