Last active
July 23, 2021 22:09
-
-
Save jrobinsonc/5718959 to your computer and use it in GitHub Desktop.
Funcion para darle formato a un número.
#javascript #numbers
This file contains hidden or 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 number_format(amount, decimals) { | |
amount += ''; // por si pasan un numero en vez de un string | |
amount = parseFloat(amount.replace(/[^0-9\.]/g, '')); // elimino cualquier cosa que no sea numero o punto | |
decimals = decimals || 0; // por si la variable no fue fue pasada | |
// si no es un numero o es igual a cero retorno el mismo cero | |
if (isNaN(amount) || amount === 0) | |
return parseFloat(0).toFixed(decimals); | |
// si es mayor o menor que cero retorno el valor formateado como numero | |
amount = '' + amount.toFixed(decimals); | |
var amount_parts = amount.split('.'), | |
regexp = /(\d+)(\d{3})/; | |
while (regexp.test(amount_parts[0])) | |
amount_parts[0] = amount_parts[0].replace(regexp, '$1' + ',' + '$2'); | |
return amount_parts.join('.'); | |
} |
Muchas Gracias!!
Gracias!!
Buen código.
Muchas gracias, me funciono muy bien.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Muchas Gracias!!!