Created
March 15, 2018 22:56
-
-
Save djom202/1a8876ab09babcb95ca756780eea373f to your computer and use it in GitHub Desktop.
Function to give them format an numbers. #javascript #numbers
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 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