For floating point numbers with multiple digits after decimal points, we may only need to retain two digits, but js does not provide such a direct function. Therefore, we have to write the function to implement this function by ourselves. The Code is as follows:
Copy codeThe 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: rounds a floating point number to the second place after the decimal point. Usage: changeTwoDecimal (3.1415926) returns 3.14 changeTwoDecimal (3.1475926) and 3.15
Js retains 2 decimal places (mandatory)
If the number of decimal places is greater than 2 digits, the above function is no problem, but if it is less than 2 digits, for example: changeTwoDecimal (3.1), 3.1 is returned, if you must use the format 3.10, you need the following function:
Copy codeThe Code 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: rounds a floating point number to the second place after the decimal point. If there are less than two digits, add 0,
This function returns the string format usage: changeTwoDecimal (3.1415926) returns 3.14 changeTwoDecimal (3.1) returns 3.10