Js formatting amount. Optional values: whether to include kilobytes of data, optional reserved precision, and found on the Internet.
Copy codeThe Code is as follows:
/*
Round the value and format it.
@ Param num value (Number or String)
@ Param cent: Number of decimal places to be retained)
@ Param isThousand whether the Sub-location is required: 0: not required, 1: required (value type );
@ Return: a string in the format of '20140901'
@ Type String
*/
Function formatNumber (num, cent, isThousand ){
Num = num. toString (). replace (/\ $ | \,/g ,'');
If (isNaN (num) // check that the input value is of the numerical type.
Num = "0 ";
If (isNaN (cent) // make sure that the input decimal point is a numeric value.
Cent = 0;
Cent = parseInt (cent );
Cent = Math. abs (cent); // obtain the number of decimal places and make sure it is a positive integer.
If (isNaN (isThousand) // make sure that the input must be of the numerical type in kilobytes.
IsThousand = 0;
IsThousand = parseInt (isThousand );
If (isThousand <0)
IsThousand = 0;
If (isThousand> = 1) // make sure that the input value is only 0 or 1
IsThousand = 1;
Sign = (num = Math. abs (num); // obtain the symbol (positive/negative)
// Math. floor: returns the maximum integer that is less than or equal to the value.
Num = Math. floor (num * Math. pow (10, cent) + 0.50000000001); // converts the specified decimal point to an integer first, and rounding out unnecessary decimal places.
Cents = num % Math. pow (10, cent); // obtain the decimal point.
Num = Math. floor (num/Math. pow (10, cent). toString (); // obtain the integer.
Cents = cents. toString (); // converts a decimal point to a string to evaluate the decimal point length.
While (cents. length <cent) {// complement the decimal point to the specified number of digits.
Cents = "0" + cents;
}
If (isThousand = 0) // you do not need a kilobytes of characters.
Return (sign )? '': '-') + Num + '.' + cents );
// Format the integer in kilobytes.
For (var I = 0; I <Math. floor (num. length-(1 + I)/3); I ++)
Num = num. substring (0, num. length-(4 * I + 3) + ',' +
Num. substring (num. length-(4 * I + 3 ));
Return (sign )? '': '-') + Num + '.' + cents );
}