JS rounds off and retains two decimal places without introducing a third-party library

Time:2020-9-15

1. toFixed()

The tofixed() method rounds number to a number of specified decimal places

Most people’s first reaction is to use ToFixed (), but there is a hole in tofixed() method

But the rounding rules are different from the rules in mathematics, which useBanker rounding rules

The essence of the so-called banker rounding method is a kind ofThe method of rounding off and taking even

In short:Round six into five consideration, after five non-zero into one, after five zero to see odd even, five before even should be discarded, five before odd to enter one

>(3.61). ToFixed (1) // rounding
'3.6'
>(3.69). ToFixed (1) // six input
'3.7'
>(3.651). ToFixed (1) // consider five, non-zero after five, advance
'3.7'
>(3.65). ToFixed (1) // consider five, zero after five, even before five, round off
'3.6'
>(3.75). ToFixed (1) // consider five, zero after five, odd before five
'3.8'

Obviously, the way we deal with the data is different from the way we deal with the data.

2. Round method

The round () method rounds a number to the nearest integer. It’s the same rule of choice in mathematics.

Math.round(X * 100) / 100

Most articles on the Internet recommend this method, but there are some problems in JavaScript about the accuracy of floating-point calculation.

//This doesn't seem to be a problem
5.1 * 100
> 509.99999999999994
Math.round(5.1 * 100) / 100
> 5.1

//Is there something wrong with this
316.655 * 100
> 31065.499999999996
Math.round(316.655 * 100) / 100
> 316.65

Here are the methods used in my project,

function fomatFloat(num, n) {
    var f = parseFloat(num);

    if (isNaN(f)) {
        return false;
    }
    f =  Math.ceil (num *  Math.pow (10, n)) /  Math.pow (10, n); // N power round up
    var s = f.toString();
    var rs = s.indexOf('.');
    //If it is an integer, add a decimal point and add 0
    if (rs < 0) {
        rs = s.length;
        s += '.';
    }
    while (s.length <= rs + n) {
        s += '0';
    }
    return s;
}