Skip to content

Instantly share code, notes, and snippets.

@sebackend
Last active March 2, 2017 19:17
Show Gist options
  • Save sebackend/2cf2ea66ffce7dcef1d946722d67b565 to your computer and use it in GitHub Desktop.
Save sebackend/2cf2ea66ffce7dcef1d946722d67b565 to your computer and use it in GitHub Desktop.
Dar formato a los números en JS, retorna un String
function formatoNumero(numero, decimales, separadorDecimal, separadorMiles) {
var partes, array;
if (!isFinite(numero) || isNaN(numero = parseFloat(numero))) {
return "";
}
if (typeof separadorDecimal === "undefined") {
separadorDecimal = ",";
}
if (typeof separadorMiles === "undefined") {
separadorMiles = "";
}
// Redondeamos
if (!isNaN(parseInt(decimales))) {
if (decimales >= 0) {
numero = numero.toFixed(decimales);
} else {
numero = (
Math.round(numero / Math.pow(10, Math.abs(decimales))) * Math.pow(10, Math.abs(decimales))
).toFixed();
}
} else {
numero = numero.toString();
}
// Damos formato
partes = numero.split(".", 2);
array = partes[0].split("");
for (var i = array.length - 3; i > 0 && array[i - 1] !== "-"; i -= 3) {
array.splice(i, 0, separadorMiles);
}
numero = array.join("");
if (partes.length > 1) {
numero += separadorDecimal + partes[1];
}
return numero;
}
//var numeroDecimal = formatoNumero(12.5, 1, ',', '.');
//var numeroMiles = formatoNumero(2500, 0, ',', '.');
//console.log(numeroDecimal); -> "12,5"
//console.log(numeroMiles); -> "2.500"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment