[Example code]:
var Number = /** * Round the value to the nearest 2 (retain 2 decimal places) and format it as an amount * * @param num * Value (Number or String) * @return A string in amount format, such as '1,234,567.45' * @type String */ formatCurrency2:function(num){ if(!num || isNaN(num)){ num ="0.00"; } num = num.toString().replace(/\$|\,/g,''); sign =(num ==(num =Math.abs(num))); num =Math.floor(num*100+0.50000000001); cents = num%100; num = Math.floor(num/100).toString();if(cents<10) cents ="0"+ cents; 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); }, /** * Round the value to the nearest 1 decimal place and format it as an amount * * @param num * Value (Number or String) * @return A string in amount format, such as '1,234,567.4' * @type String */ formatCurrency1:function(num){ if(!num || isNaN(num)){ num ="0.0"; } num = num.toString().replace(/\$|\,/g,''); sign =(num ==(num =Math.abs(num))); num =Math.floor(num*10+0.50000000001); cents = num%10; num =Math.floor(num/10).toString(); 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); }, formatCurrency:function(num){ if(!num || isNaN(num)){ num ="0.00"; } var t = num, i, r;debugger; for( t = t.toString().replace(/^(\d*)$/,"$1."), t =(t +"00").replace(/(\d*\.\d\d)\d*/,"$1"), t = t.replace(".",","), i =/(\d)(\d{3},)/; i.test(t);){ t = t.replace(i,"$1,$2"); } return t = t.replace(/,(\d\d)$/,".$1"), r = t.split("."), r[1]=="00"&&(t = r[0]), t } };
[Test code]:
console.info(Number.formatCurrency2(123232)); console.info(Number.formatCurrency2()); console.info(Number.formatCurrency2('')); console.info(Number.formatCurrency2("")); console.info(Number.formatCurrency1(123232)); console.info(Number.formatCurrency1()); console.info(Number.formatCurrency1('')); console.info(Number.formatCurrency1("")); console.info(Number.formatCurrency(123232.999)); console.info(Number.formatCurrency()); console.info(Number.formatCurrency('')); console.info(Number.formatCurrency(""));
【Print result】:
123,232.00 0.00 0.00 0.00 123,232.0 0.0 0.0 0.0 123,232.99 0.00 0.00 0.00
Donor sharer
I didn't like programming before, but now I am an IT fan obsessed with programming. I would like to share some things I have sorted out and optimized here, hoping to help IT fans, with joy and sweat, and at the same time I also hope that everyone can support it. Of course, if you have money to support a money field (support Alipay and WeChat donations, join the it data center buckle group), but have no money to support a personal field, with your support, we will be more motivated and do better, thank you Ladies and gentlemen.