Last active
January 25, 2017 21:33
-
-
Save dustinpoissant/8d6dddef7cdd49fca5262d900b02e8ae to your computer and use it in GitHub Desktop.
A JavaScript function to format a number into a string.
This file contains hidden or 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 formatNumber(v, format){ | |
if(format.indexOf(".")>-1){ | |
var neg = false; | |
if(v<0)neg = true; | |
v = Math.abs(v); | |
var bd = format.indexOf("."); | |
var ad = format.length-bd-1; | |
var b = Math.floor(v); | |
var a = v - b; | |
b+=""; | |
while(b.length < bd) | |
b="0"+b; | |
if(a==0){ | |
a = ""; | |
while(a.length < ad) | |
a+="0"; | |
} else { | |
a = Math.round(a*Math.pow(10, ad)); | |
} | |
if(neg) | |
return "-"+b+"."+a; | |
else | |
return b+"."+a; | |
} else { | |
var bd = format.length; | |
b=Math.round(v)+""; | |
while(b.length < bd) | |
b="0"+b; | |
return b; | |
} | |
}; |
This file contains hidden or 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 formatNumber(a,b){if(b.indexOf(".")>-1){var c=!1;a<0&&(c=!0),a=Math.abs(a);var d=b.indexOf("."),e=b.length-d-1,f=Math.floor(a),g=a-f;for(f+="";f.length<d;)f="0"+f;if(0==g)for(g="";g.length<e;)g+="0";else g=Math.round(g*Math.pow(10,e));return c?"-"+f+"."+g:f+"."+g}var d=b.length;for(f=Math.round(a)+"";f.length<d;)f="0"+f;return f}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment