Created
February 8, 2018 21:31
-
-
Save castrolol/3970efaa936d20c9eb6031b245bc2b0b to your computer and use it in GitHub Desktop.
Format Number.js
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 formatNumber(valor, places) { | |
places = +places || 0; | |
if (typeof valor == 'undefined' || valor == null) return ''; | |
valor = +valor; | |
if (isNaN(valor)) return '--'; | |
var milhar = ''; | |
var valorFinal = ''; | |
var inteiro = valor.toFixed(places); | |
var decimal = ''; | |
if (places) { | |
var pieces = inteiro.split('.'); | |
inteiro = pieces[0]; | |
decimal = pieces[1]; | |
} | |
for (var i = inteiro.length - 1; i >= 0; i--) { | |
milhar = inteiro[i] + milhar; | |
if (milhar.length == 3) { | |
if (i) milhar = '.' + milhar; | |
valorFinal = milhar + valorFinal; | |
milhar = ''; | |
} | |
} | |
valorFinal = milhar + valorFinal + (places ? ',' + decimal : ''); | |
return valorFinal; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment