JavaScript retains two custom functions with two decimal places

  • 2020-03-30 02:48:03
  • OfStack

For some floating point Numbers with multiple decimal points, we may only need to keep 2 bits, but js does not provide such a direct function, so we have to write our own function to achieve this function, the code is as follows:


function changeTwoDecimal(x) {
    var f_x = parseFloat(x);
    if (isNaN(f_x)) {
        alert('function:changeTwoDecimal->parameter error');
        return false;
    }
    var f_x = Math.round(x * 100) / 100;
    return f_x;
}

Function: round a floating-point number to two decimal places: changeTwoDecimal(3.1415926) returns 3.14 changeTwoDecimal(3.1475926) returns 3.15


Js keep 2 decimal places (mandatory)

For decimal places larger than 2, the above function is fine, but for decimal places smaller than 2, such as changeTwoDecimal(3.1), will return 3.1.


function changeTwoDecimal_f(x) {
    var f_x = parseFloat(x);
    if (isNaN(f_x)) {
        alert('function:changeTwoDecimal->parameter error');
        return false;
    }
    var f_x = Math.round(x * 100) / 100;
    var s_x = f_x.toString();
    var pos_decimal = s_x.indexOf('.');
    if (pos_decimal < 0) {
        pos_decimal = s_x.length;
        s_x += '.';
    }
    while (s_x.length <= pos_decimal + 2) {
        s_x += '0';
    }
    return s_x;
}

Function: round the floating point number to 2 places after the decimal point. If there are less than 2 places, fill 0.
This function returns the format usage of the string: changeTwoDecimal(3.1415926) returns 3.14 changeTwoDecimal(3.1) returns 3.10


Related articles: