Home > Web Front-end > JS Tutorial > body text

js formatted amount optional with thousandths and preservation of precision_javascript skills

WBOY
Release: 2016-05-16 17:01:57
Original
1009 people have browsed it

js formatted amount, optional with or without thousandths, optional retention of precision, also found online, but no problem to use

Copy code The code is as follows:

/*
Round the value and format it.
@param num value (Number or String)
@param cent The decimal to be retained Bit (Number)
@param isThousand whether thousandth place is required 0: not required, 1: required (numeric type);
@return string in 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))//Ensure that the incoming decimal place is a numeric value.
cent = 0;
cent = parseInt(cent);
cent = Math.abs(cent);//Find the number of decimal places and make sure it is a positive integer.
if(isNaN(isThousand))//Make sure whether the input is required Thousands is a numeric type.
isThousand = 0;
isThousand = parseInt(isThousand);
if(isThousand < 0)
isThousand = 0;
if(isThousand >= 1) //Make sure the value passed in is only 0 or 1
isThousand = 1;
sign = (num == (num = Math.abs(num))); //Get the sign (positive/negative number )
//Math.floor: Returns the largest integer less than or equal to its numerical parameter
num = Math.floor(num*Math.pow(10,cent) 0.50000000001);//Convert the specified decimal places first into an integer. Extra decimal places are rounded off.
cents = num%Math.pow(10,cent); //Find the decimal place value.
num = Math.floor(num/Math.pow(10, cent)).toString();//Find the integer digit value.
cents = cents.toString();//Convert the decimal digits into a string to find the length of the decimal digits.
while(cents. lengthcents = "0" cents;
}
if(isThousand == 0) //No thousandth place character required.
return (((sign)?'':'-') num '.' cents);
//Format the integer part into thousandths.
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);
}
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!