After trying many different solutions, this seems (to me) the best way:
JS Fiddle demo
(1234568).toLocaleString("en-US", {style: "decimal", minimumFractionDigits: 2});
or
var opts = '{style: "decimal", currency: "USD", minimumFractionDigits: 2}';
(1234568).toLocaleString("en-US", opts);
or
(1234568).toLocaleString("en-US", {style: "decimal", minimumFractionDigits: 0});
I liked NickG's comment from mid-2013: "Agreed, it's not fully supported across all browsers (yet), but it's still a solution. (And arguably the most valid solution, as its forward compatible with the non-supported browsers, and it's a documented feature of the JavaScript api.)"
Sources:
How to format numbers as currency strings
How to format a number with commas as thousands separators?
Answer from crashwap on Stack OverflowVideos
After trying many different solutions, this seems (to me) the best way:
JS Fiddle demo
(1234568).toLocaleString("en-US", {style: "decimal", minimumFractionDigits: 2});
or
var opts = '{style: "decimal", currency: "USD", minimumFractionDigits: 2}';
(1234568).toLocaleString("en-US", opts);
or
(1234568).toLocaleString("en-US", {style: "decimal", minimumFractionDigits: 0});
I liked NickG's comment from mid-2013: "Agreed, it's not fully supported across all browsers (yet), but it's still a solution. (And arguably the most valid solution, as its forward compatible with the non-supported browsers, and it's a documented feature of the JavaScript api.)"
Sources:
How to format numbers as currency strings
How to format a number with commas as thousands separators?
You could have provided some inputs and corresponding outputs to describe your problem clearer. I assume you need a function that gets as input any non-negative number and want as output a string formatted with decimal point and thousand-separators. If my assumption is true the following might help you, tested on firefox 24.0 /Linux:
<!DOCTYPE html>
<html>
<head>
<title>HTML</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
var decimalSeparator = ".";
var decimalDefault = decimalSeparator + "00";
var thousandsSeparator = ",";
/**
* @param {String or Number} value The value to format
* @returns {String} The formatted Number as a String
*/
function formatMoney(value) {
var valueStr = String(value);
var decimalDividerPos = valueStr.indexOf(".");
var decimalPart = decimalDividerPos == -1 ? decimalDefault : decimalSeparator + valueStr.substr(decimalDividerPos + 1);
var integerPart = decimalDividerPos == -1 ? valueStr : valueStr.substring(0, decimalDividerPos);
var integerAry = new Array();
var lenTemp = 0;
for (var i = integerPart.length - 1; i >= 0; i--) {
integerAry.unshift(integerPart.substr(i, 1));
if (i && (!(++lenTemp % 3))) {
integerAry.unshift(thousandsSeparator);
}
}
return integerAry.join("") + decimalPart;
}
</script>
<body>
<script type="text/javascript">
var testValues = new Array(
0, 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000,
0.9876, 1.9876, 10.9876, 100.9876, 1000.9876, 10000.9876, 100000.9876, 1000000.9876, 10000000.9876,
1234567e+123, Number.MAX_VALUE);
for (var x in testValues) {
console.log("VALUE=" + testValues[x] + " => FORMATTED=" + formatMoney(testValues[x]));
}
</script>
</body>
</html>
I used the idea from Kerry's answer, but I simplified it since I was just looking for something simple for my specific purpose. Here is what I have:
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function numberWithCommas(x) {
return x.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
}
function test(x, expect) {
const result = numberWithCommas(x);
const pass = result === expect;
console.log(`${pass ? "✓" : "ERROR ====>"}
{result}`);
return pass;
}
let failures = 0;
failures += !test(0, "0");
failures += !test(100, "100");
failures += !test(1000, "1,000");
failures += !test(10000, "10,000");
failures += !test(100000, "100,000");
failures += !test(1000000, "1,000,000");
failures += !test(10000000, "10,000,000");
if (failures) {
console.log(`${failures} test(s) failed`);
} else {
console.log("All tests passed");
}
.as-console-wrapper {
max-height: 100% !important;
}
The regex uses two lookahead assertions:
- a positive one to look for any point in the string that has a multiple of 3 digits in a row after it,
- a negative assertion to make sure that point only has exactly a multiple of 3 digits. The replacement expression puts a comma there.
For example, if you pass it 123456789.01, the positive assertion will match every spot to the left of the 7 (since 789 is a multiple of 3 digits, 678 is a multiple of 3 digits, 567, etc.).
The negative assertion checks that the multiple of 3 digits does not have any digits after it. 789 has a period after it so it is exactly a multiple of 3 digits, so a comma goes there. 678 is a multiple of 3 digits, but it has a 9 after it, so those 3 digits are part of a group of 4, and a comma does not go there. Similarly for 567.
456789 is 6 digits, which is a multiple of 3, so a comma goes before that. 345678 is a multiple of 3, but it has a 9 after it, so no comma goes there. And so on. The \B keeps the regex from putting a comma at the beginning of the string.
neu-rah mentioned that this function adds commas in undesirable places if there are more than 3 digits after the decimal point. If this is a problem, you can use this function:
function numberWithCommas(x) {
var parts = x.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return parts.join(".");
}
function numberWithCommas(x) {
var parts = x.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return parts.join(".");
}
function test(x, expect) {
const result = numberWithCommas(x);
const pass = result === expect;
console.log(`${pass ? "✓" : "ERROR ====>"}
{result}`);
return pass;
}
let failures = 0;
failures += !test(0 , "0");
failures += !test(0.123456 , "0.123456");
failures += !test(100 , "100");
failures += !test(100.123456 , "100.123456");
failures += !test(1000 , "1,000");
failures += !test(1000.123456 , "1,000.123456");
failures += !test(10000 , "10,000");
failures += !test(10000.123456 , "10,000.123456");
failures += !test(100000 , "100,000");
failures += !test(100000.123456 , "100,000.123456");
failures += !test(1000000 , "1,000,000");
failures += !test(1000000.123456 , "1,000,000.123456");
failures += !test(10000000 , "10,000,000");
failures += !test(10000000.123456, "10,000,000.123456");
if (failures) {
console.log(`${failures} test(s) failed`);
} else {
console.log("All tests passed");
}
.as-console-wrapper {
max-height: 100% !important;
}
T.J. Crowder pointed out that now that JavaScript has lookbehind (support info), it can be solved in the regular expression itself:
function numberWithCommas(x) {
return x.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
}
function numberWithCommas(x) {
return x.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
}
function test(x, expect) {
const result = numberWithCommas(x);
const pass = result === expect;
console.log(`${pass ? "✓" : "ERROR ====>"}
{result}`);
return pass;
}
let failures = 0;
failures += !test(0, "0");
failures += !test(0.123456, "0.123456");
failures += !test(100, "100");
failures += !test(100.123456, "100.123456");
failures += !test(1000, "1,000");
failures += !test(1000.123456, "1,000.123456");
failures += !test(10000, "10,000");
failures += !test(10000.123456, "10,000.123456");
failures += !test(100000, "100,000");
failures += !test(100000.123456, "100,000.123456");
failures += !test(1000000, "1,000,000");
failures += !test(1000000.123456, "1,000,000.123456");
failures += !test(10000000, "10,000,000");
failures += !test(10000000.123456, "10,000,000.123456");
if (failures) {
console.log(`${failures} test(s) failed`);
} else {
console.log("All tests passed");
}
.as-console-wrapper {
max-height: 100% !important;
}
(?<!\.\d*) is a negative lookbehind that says the match can't be preceded by a . followed by zero or more digits. The negative lookbehind is faster than the split and join solution (comparison), at least in V8.
I'm surprised nobody mentioned Number.prototype.toLocaleString. It's implemented in JavaScript 1.5 (which was introduced in 1999), so it's basically supported across all major browsers.
var n = 34523453.345;
console.log(n.toLocaleString()); // "34,523,453.345"
It also works in Node.js as of v0.12 via inclusion of Intl.
If you want something different, Numeral.js might be interesting.
Intl.NumberFormat
JavaScript has a number formatter (part of the Internationalization API).
// Create our number formatter.
const formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
// These options can be used to round to whole numbers.
trailingZeroDisplay: 'stripIfInteger' // This is probably what most people
// want. It will only stop printing
// the fraction when the input
// amount is a round number (int)
// already. If that's not what you
// need, have a look at the options
// below.
//minimumFractionDigits: 0, // This suffices for whole numbers, but will
// print 2500.10 as $2,500.1
//maximumFractionDigits: 0, // Causes 2500.99 to be printed as $2,501
});
// Use the formatter with the value of an input.
let input = document.getElementById('amount');
input.addEventListener('keyup', e => {
document.getElementById('result').innerText = formatter.format(e.target.value);
});
input.dispatchEvent(new Event('keyup'));
<label>
Amount
<input id="amount" value="2500">
</label>
Result:
<span id="result"></span>
Use undefined in place of the first argument ('en-US' in the example) to use the system locale (the user locale in case the code is running in a browser). Further explanation of the locale code.
Here's a list of the currency codes.
Intl.NumberFormat vs Number.prototype.toLocaleString
A final note comparing this to the older .toLocaleString. They both offer essentially the same functionality. However, toLocaleString in its older incarnations (pre-Intl) does not actually support locales: it uses the system locale. So when debugging old browsers, be sure that you're using the correct version (MDN suggests to check for the existence of Intl). There isn't any need to worry about this at all if you don't care about old browsers or just use the shim.
Also, the performance of both is the same for a single item, but if you have a lot of numbers to format, using Intl.NumberFormat is ~70 times faster. Therefore, it's usually best to use Intl.NumberFormat and instantiate only once per page load. Anyway, here's the equivalent usage of toLocaleString:
console.log((2500).toLocaleString('en-US', {
style: 'currency',
currency: 'USD',
})); /* $2,500.00 */
Some notes on browser support and Node.js
- Browser support is no longer an issue nowadays with 99+% support globally
- There is a shim to support it on fossilized browsers (like Internet Explorer 8), should you really need to
- Node.js before v13 only supports
en-USout of the box. One solution is to install full-icu, see here for more information - Have a look at CanIUse for more information
Number.prototype.toFixed
This solution is compatible with every single major browser:
const profits = 2489.8237;
profits.toFixed(3) // Returns 2489.824 (rounds up)
profits.toFixed(2) // Returns 2489.82
profits.toFixed(7) // Returns 2489.8237000 (pads the decimals)
All you need is to add the currency symbol (e.g. "$" + profits.toFixed(2)) and you will have your amount in dollars.
Custom function
If you require the use of , between each digit, you can use this function:
function formatMoney(number, decPlaces, decSep, thouSep) {
decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces,
decSep = typeof decSep === "undefined" ? "." : decSep;
thouSep = typeof thouSep === "undefined" ? "," : thouSep;
var sign = number < 0 ? "-" : "";
var i = String(parseInt(number = Math.abs(Number(number) || 0).toFixed(decPlaces)));
var j = (j = i.length) > 3 ? j % 3 : 0;
return sign +
(j ? i.substr(0, j) + thouSep : "") +
i.substr(j).replace(/(\decSep{3})(?=\decSep)/g, "$1" + thouSep) +
(decPlaces ? decSep + Math.abs(number - i).toFixed(decPlaces).slice(2) : "");
}
document.getElementById("b").addEventListener("click", event => {
document.getElementById("x").innerText = "Result was: " + formatMoney(document.getElementById("d").value);
});
<label>Insert your amount: <input id="d" type="text" placeholder="Cash amount" /></label>
<br />
<button id="b">Get Output</button>
<p id="x">(press button to get output)</p>
Use it like so:
(123456789.12345).formatMoney(2, ".", ",");
If you're always going to use '.' and ',', you can leave them off your method call, and the method will default them for you.
(123456789.12345).formatMoney(2);
If your culture has the two symbols flipped (i.e., Europeans) and you would like to use the defaults, just paste over the following two lines in the formatMoney method:
d = d == undefined ? "," : d,
t = t == undefined ? "." : t,
Custom function (ES6)
If you can use modern ECMAScript syntax (i.e., through Babel), you can use this simpler function instead:
function formatMoney(amount, decimalCount = 2, decimal = ".", thousands = ",") {
try {
decimalCount = Math.abs(decimalCount);
decimalCount = isNaN(decimalCount) ? 2 : decimalCount;
const negativeSign = amount < 0 ? "-" : "";
let i = parseInt(amount = Math.abs(Number(amount) || 0).toFixed(decimalCount)).toString();
let j = (i.length > 3) ? i.length % 3 : 0;
return negativeSign +
(j ? i.substr(0, j) + thousands : '') +
i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands) +
(decimalCount ? decimal + Math.abs(amount - i).toFixed(decimalCount).slice(2) : "");
} catch (e) {
console.log(e)
}
};
document.getElementById("b").addEventListener("click", event => {
document.getElementById("x").innerText = "Result was: " + formatMoney(document.getElementById("d").value);
});
<label>Insert your amount: <input id="d" type="text" placeholder="Cash amount" /></label>
<br />
<button id="b">Get Output</button>
<p id="x">(press button to get output)</p>