Posts Tagged ‘javascript like php number_format’

Javascript format number function like php number_format

Tuesday, April 10th, 2012

function numFormat(thisNum,dec){
// 133.88888, 2
// like phps format function
if( !thisNum ){ return 0; }
thisNum = thisNum.toString();
var Integer = thisNum.split(“.”);
var Principal = Integer[0];
var Decimal = 0;
if( Integer[1] != ” && dec != 0 ){
Decimal = (Integer[1]).substring(0,(dec*1)); // drop decimal after requested
} else {
Decimal = “”;
}
if( Principal > 1000 ){
Principal = Principal.toString();
if( Principal.length == 4 ){
// xxxx.xxxx => x,xxx.xx
var retStr = Principal[0] + “,” + Principal[1] + Principal[2] + Principal[3];
} else if( Principal.length == 5 ){
var retStr = Principal[0] + Principal[1] + “,” + Principal[2] + Principal[3] + Principal[4];
}
else if( Principal.length == 6 ){
var retStr = Principal[0] + Principal[1] + Principal[2] + “,” + Principal[3] + Principal[4] + Principal[5];
}
else {
retStr = Principal;
}
retStr += ( Decimal != ” ? “.” + Decimal : ” );
return retStr;
} else {
return Integer[0] + “.” + Decimal;
}
}