For some decimal point after a number of floating-point numbers, we may only need to retain 2 bits, but JS does not provide such a direct function, so we have to write the function to implement this function, the code is as follows:
Copy Code code 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: Rounding floating-point numbers, taking the 2-bit usage after the decimal point: Changetwodecimal (3.1415926) returns 3.14 Changetwodecimal (3.1475926) returns 3.15
JS retains 2 decimal places (mandatory)
For decimal digits greater than 2 digits, use the above function is OK, but if less than 2 bits, such as: Changetwodecimal (3.1), will return 3.1, if you must need a format such as 3.10, then you need the following function:
Copy code code 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: Rounding floating-point numbers, taking 2 digits after the decimal point, or 0 if less than 2 digits,
This function returns the format usage of the string: Changetwodecimal (3.1415926) returns 3.14 Changetwodecimal (3.1) returns 3.10