For some floating point numbers with multiple digits after the decimal point, we may only need to keep 2 digits, but js does not provide such a direct function, so we have to write the function ourselves to implement this function, the code is as follows:
The code copy 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 floating point numbers and take 2 decimal points Usage: changeTwoDecimal(3.1415926) returns 3.14 changeTwoDecimal(3.1475926) returns 3.15
js retains 2 decimal places (forced)
For decimal places with a decimal point greater than 2 digits, it is no problem to use the above function, but if it is less than 2 digits, for example: changeTwoDecimal(3.1), it will return 3.1. If you must need a format like 3.10, then you need the following function:
The code copy is as follows:
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 floating point number, take 2 decimal places, if less than 2 digits, add 0,
This function returns the format usage of the string: changeTwoDecimal(3.1415926) returns 3.14 changeTwoDecimal(3.1) returns 3.10