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

js formatted currency data implementation code_javascript skills

WBOY
Release: 2016-05-16 17:23:32
Original
954 people have browsed it
Copy code The code is as follows:

function formatCurrency(num) {
var sign="";
if(isNaN(num))
{
num = 0;
}
if(num<0)
{
sign="-";
}
var strNum=num "";
var arr1 = strNum.split(".");
var hasPoint=false;//Whether there is a decimal part
var piontPart="";/ /Decimal part
var intPart=strNum;//Integer part
if(arr1.length>=2)
{
hasPoint=true;
piontPart= arr1[1];
intPart=arr1[0];
}

var res='';//Save the part with comma added
var intPartlength=intPart.length;//Integer part length
var maxcount=Math.ceil(intPartlength/3);//How many commas need to be added to the integer part
for (var i = 1; i <=maxcount;i)//Add one comma for every three digits
{
var startIndex=intPartlength-i*3;//Start position
if(startIndex<0)//When the start position is less than 0, it is corrected to 0
{
startIndex=0;
}
var endIndex=intPartlength-i*3 3;//End position
var part=intPart.substring(startIndex,endIndex) ",";
res=part res;
}
res=res.substr(0,res.length-1);//Remove the last comma
if(hasPoint)
{
return "¥" sign res "." piontPart;
}
else
{
return "¥" sign res;
}

}
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!