Last active
December 14, 2016 14:30
-
-
Save belchior/c53824ba9c1346ced8c5fd5376d61448 to your computer and use it in GitHub Desktop.
Convert Number and String with number to brazilian currency
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 brazilianCurrency(money, decimalEmbeded) { | |
var decimalPart; | |
if (decimalEmbeded) { // example R$72,35 is 7235 | |
money = String(money); | |
money = 'R$ ' + Number(money.slice(0, -2)).toLocaleString().replace(/,/g, '.') + ',' + money.slice(-2); | |
} else { | |
money = 'R$ ' + Number(money).toLocaleString().replace(/,/g, ';').replace(/\./g, ',').replace(/;/g, '.'); | |
if (money.search(',') >= 0) { | |
decimalPart = money.split(',').pop(); | |
decimalPart = decimalPart.length === 1 ? decimalPart + '0' : decimalPart; | |
money = money.split(',').shift() + ',' + decimalPart; | |
} else { | |
money = money + ',00'; | |
} | |
} | |
return money; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: