Skip to content

Instantly share code, notes, and snippets.

@vlrmprjct
Last active May 4, 2017 09:20
Show Gist options
  • Save vlrmprjct/ce27e468ff47ba6cca9f to your computer and use it in GitHub Desktop.
Save vlrmprjct/ce27e468ff47ba6cca9f to your computer and use it in GitHub Desktop.
Number Formatting Using string.replace in JavaScript
// 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 €
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