Last active
February 11, 2016 12:51
-
-
Save fernandodof/82051c5202dd7f3f269e to your computer and use it in GitHub Desktop.
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
<!DOCTYPE html> | |
<html> | |
<body> | |
<p>Click the button to display the fixed number.</p> | |
<button onclick="myFunction('99999999999998.5900', '', 0, '.', ',')">Try it</button> | |
<p>1</p> | |
<p id="demo"></p> | |
<p>2</p> | |
<p id="demo2"></p> | |
<p>3</p> | |
<p id="demo3"></p> | |
<p>4</p> | |
<p id="demo4"></p> | |
<script> | |
function myFunction(valor, simboloMonetario, casasDecimais, separadorMilhar, separadorDecimal) { | |
if(!valor.match(/^[0-9]+\.[0-9]{1,4}$/)){ | |
return valor; | |
} | |
var milhares = 3; | |
casasDecimais = casasDecimais !== true ? casasDecimais : 2; | |
simboloMonetario = simboloMonetario !== undefined ? simboloMonetario : "R$ "; | |
separadorMilhar = separadorMilhar || "."; | |
separadorDecimal = separadorDecimal || ","; | |
var parteInteira; | |
var parteDecimal; | |
var valorArray = valor.split('.'); | |
parteInteira = valorArray[0]; | |
parteDecimal = valorArray[1]; | |
parteDecimal = parteDecimal.substr(0, casasDecimais); | |
while(parteDecimal.charAt(parteDecimal.length-1) == '0'){ | |
parteDecimal = parteDecimal.slice(0, -1); | |
} | |
if(!casasDecimais){ | |
separadorDecimal = ''; | |
} | |
parteInteira = parteInteira.toString().replace(/\B(?=(\d{3})+(?!\d))/g, separadorMilhar); | |
var resultado = simboloMonetario + parteInteira + separadorDecimal + parteDecimal; | |
//document.getElementById("demo").innerHTML = parteInteira + ' - ' + parteInteira.length; | |
document.getElementById("demo2").innerHTML = parteDecimal; | |
document.getElementById("demo3").innerHTML = 'resultado ' + resultado; | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment