Skip to content

Instantly share code, notes, and snippets.

@castrolol
Created February 8, 2018 21:31
Show Gist options
  • Save castrolol/3970efaa936d20c9eb6031b245bc2b0b to your computer and use it in GitHub Desktop.
Save castrolol/3970efaa936d20c9eb6031b245bc2b0b to your computer and use it in GitHub Desktop.
Format Number.js
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