-
-
Save felipedes/257bb139986c4c2d65f4fe5533db0cb7 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('.'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment