JS format amount, optional whether with thousand points, optional retention accuracy, but also found on the Internet, but the use of no problem
Copy Code code as follows:
/*
The values are rounded and formatted.
@param num Value (number or string)
@param number of decimal places to keep cent
@param whether the Isthousand need to be 0: not required, 1: required (numerical type);
A string @return format, such as ' 1,234,567.45 '
@type String
*/
function FormatNumber (Num,cent,isthousand) {
num = num.tostring (). Replace (/\$|\,/g, "");
if (isNaN (num))//check that the incoming value is a numeric type.
num = "0";
if (isNaN (cent))//ensures that incoming decimal places are numeric values.
cent = 0;
cent = parseint (cent);
cent = math.abs (cent);//Find the number of decimal places to ensure a positive integer.
if (isNaN (Isthousand))//ensures that the thousand-bit value type is required for incoming.
Isthousand = 0;
Isthousand = parseint (Isthousand);
if (Isthousand < 0)
Isthousand = 0;
if (Isthousand >=1)//Ensure that the number passed in is only 0 or 1
Isthousand = 1;
Sign = (num = (num = math.abs (num));/get symbol (positive/negative)
Math.floor: Returns the largest integer less than or equal to its numeric argument
num = Math.floor (Num*math.pow (10,cent) +0.50000000001);//converts the specified decimal places to integers. Extra decimal places rounded.
cents = Num%math.pow (10,cent); Find the decimal digit value.
num = Math.floor (Num/math.pow (10,cent)). toString ();//Find an integer digit value.
cents = cents.tostring ();//converts decimal places to strings to find decimal lengths.
while (cents.length<cent) {//complements the decimal places to the specified number of digits.
cents = "0" + cents;
}
if (Isthousand = = 0)//no thousand characters are required.
Return (((sign)? ': '-') + num + '. ' + cents);
The integer portion is formatted as a decimal point.
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);
}