This article mainly introduces the two udfs that retain two decimal places in JavaScript. For more information, see some floating point numbers with multiple decimal places. We may only need to keep two digits, but js does not provide such a direct function, so we have to write our own function to implement this function. The Code is as follows:
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: 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:
The 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