Created
July 12, 2012 16:06
-
-
Save demian85/3099066 to your computer and use it in GitHub Desktop.
JS number format func
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function numberFormat(number, dec, dsep, tsep) { | |
if (isNaN(number)) return ""; | |
number = number.toFixed(dec || 0); | |
var pindex = number.indexOf('.'), fnums, decimals, parts = []; | |
if (pindex > -1) { | |
fnums = number.substring(0, pindex).split(''); | |
decimals = (dsep || '.') + number.substr(pindex+1); | |
} | |
else { | |
fnums = number.split(''); | |
decimals = ''; | |
} | |
do { | |
parts.unshift(fnums.splice(-3, 3).join('')); | |
} while (fnums.length); | |
return parts.join(tsep || ',') + decimals; | |
} | |
// test... | |
var nums = { | |
"numberFormat2(90000)" : numberFormat2(90000), | |
"numberFormat2(90000, 2)" : numberFormat2(90000, 2), | |
"numberFormat2(1000.754)" : numberFormat2(1000.754), | |
"numberFormat2(1000.754, 2)" : numberFormat2(1000.754, 2), | |
"numberFormat2(1000.754, 0, ',', '.')" : numberFormat2(1000.754, 0, ',', '.'), | |
"numberFormat2(1000.754, 2, ',', '.')" : numberFormat2(1000.754, 2, ',', '.'), | |
"numberFormat2(1000000000)" : numberFormat2(1000000000), | |
"numberFormat2(1000000000.987654, 2)" : numberFormat2(1000000000.987654, 2) | |
} | |
Object.keys(nums).forEach(function(k) { | |
console.log(k + ' ' + nums[k]); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment