Created
August 28, 2012 14:12
-
-
Save fernandosavio/3498361 to your computer and use it in GitHub Desktop.
Format currency or just input milliar and decimal delimiters
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
//standalo ie9+ code | |
/** | |
* @param v Number Number to be formatted | |
* @param m String Milliar delimitter. Default: '.' (pt-br). | |
* @param d String Decimal delimitter. Default: ',' (pt-br). | |
* @return String Formatted number | |
*/ | |
function formatCurrency(v,m,d){ | |
var r = v.toFixed(2).split(/\.|-/), | |
m = m || '.', | |
d = d || ',', | |
n = r.length-2 ? '-' : ''; | |
r = r.slice(r.length-2); | |
if(isNaN(+v) || !v) return '0,00'; | |
return n+r[0].split('').reduce(function(x,y,i,a){ return x+(((a.length-i)%3 == 0)?m:"")+y})+d+r[1]; | |
} | |
//polyfill ie6+ code | |
function lPad (str, padString, length) { | |
while (str.length < length) { | |
str = padString + str; | |
} | |
return str; | |
} | |
function formatValor(valor){ | |
var result = [], i, n="" ; | |
if( isNaN(+valor) || !valor) return '0,00'; | |
if(valor < 0){ | |
valor *= -1; | |
n='-'; | |
} | |
valor = (+valor).toFixed(2).split('.'); | |
for(i = +valor[0] ; i ; i = Math.floor(i/1000)){ | |
result.unshift("" + lPad((i%1000)+"",'0' ,3 )); | |
} | |
result[0] = +result[0] + ""; | |
return n+result.join('.') + "," + valor[1]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment