Search code examples
javascriptrounding

How do you round to one decimal place in JavaScript?


Can you round a number in JavaScript to one character after the decimal point (properly rounded)?

I tried the *10, round, /10, but it leaves two decimals at the end of the int.


Solution

  • Math.round(num * 10) / 10 works, and here is an example...

    var number = 12.3456789
    var rounded = Math.round(number * 10) / 10
    // rounded is 12.3
    

    If you want it to have one decimal place, even when that would be a 0, then add...

    var fixed = rounded.toFixed(1)
    // 'fixed' is always to one decimal point
    // NOTE: .toFixed() returns a string!
    
    // To convert back to number format
    parseFloat(number.toFixed(2))
    // 12.34
    // but that will not retain any trailing zeros
    
    // So, just make sure it is the last step before output,
    // and use a number format during calculations!
    

    Using this principle, for reference, here is a handy little round function that takes precision...

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

    ... usage ...

    round(12345.6789, 2) // 12345.68
    round(12345.6789, 1) // 12345.7
    

    ... defaults to round to nearest whole number (precision 0) ...

    round(12345.6789) // 12346
    

    ... and can be used to round to nearest 10 or 100, etc...

    round(12345.6789, -1) // 12350
    round(12345.6789, -2) // 12300
    

    ... and correct handling of negative numbers ...

    round(-123.45, 1) // -123.4
    round(123.45, 1) // 123.5
    

    ... and can be combined with toFixed to format consistently as string ...

    round(456.7, 2).toFixed(2) // "456.70"