Last active
May 4, 2017 09:20
-
-
Save vlrmprjct/ce27e468ff47ba6cca9f to your computer and use it in GitHub Desktop.
Number Formatting Using string.replace in JavaScript
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
// SOURCE: http://blog.tompawlak.org/number-currency-formatting-javascript | |
function formatNumber (num) { | |
return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"); | |
} | |
console.info(formatNumber(2665)); // 2,665 | |
console.info(formatNumber(102665)); // 102,665 | |
console.info(formatNumber(111102665)); // 111,102,665 | |
console.info(formatNumber(1240.5)); // 1,240.5 | |
console.info(formatNumber(1000240.5)); // 1,000,240.5 | |
function currencyFormat (num) { | |
return "$" + num.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"); | |
} | |
console.info(currencyFormat(2665)); // $2,665.00 | |
console.info(currencyFormat(102665)); // $102,665.00 | |
function currencyFormatDE (num) { | |
return num | |
.toFixed(2) // always two decimal digits | |
.replace(".", ",") // replace decimal point character with , | |
.replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1.") + " €"; // use . as a separator | |
} | |
console.info(currencyFormatDE(1234567.89)); // output 1.234.567,89 € |
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
var formatInt = function (num) { | |
num = parseFloat(num); | |
return num.toLocaleString('de-DE', {minimumFractionDigits: 2}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment