There are quite a few ways to format a number as a currency value in Javascript.
Doing it yourself
The easiest of which is that of using the built-in toFixed()
method.
Often times you will either have a string, integer or floating-point number (/double) and will need to output a value that looks like a currency.
So this: 12345.67120398
should become this: 12,345.67
.
Let’s take the following example:
var yourBalance = 2489.8237; //returns 2489.824 (rounds up) yourBalance.toFixed(3); //returns 2489.82 yourBalance.toFixed(2); //returns 2489.8237000 (pads the decimals) yourBalance.toFixed(7);
But what about formatting the “thousands”, or “millions” sections?
A winning short and fast
solution would be to use the following:
// input: `12345.67` (12345.67).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,'); // output: `12,345.67`
If we run the above short and fast
solution against a range of values, we can see how it plays out in the following output:
1 --> "1.00" 12 --> "12.00" 123 --> "123.00" 1234 --> "1,234.00" 12345 --> "12,345.00" 123456 --> "123,456.00" 1234567 --> "1,234,567.00" 12345.67 --> "12,345.67"
This is pretty good, so let’s go one step further and create a more sophisticated prototype function we can use on all Number
types:
Number.prototype.format = function(len, w_part, s_delim, c_delim) { var re = '\\d(?=(\\d{' + (w_part || 3) + '})+' + (len > 0 ? '\\D' : '$') + ')', num = this.toFixed(Math.max(0, ~~len)); return (c_delim ? num.replace('.', c_delim) : num).replace(new RegExp(re, 'g'), '$&' + (s_delim || ',')); };
Now we get to use our new Number prototype extension method:
12345678.9.format(2, 3, '.', ','); // "12.345.678,90" 12345678.9.format(0, 3, '-'); // "12-345-679" 123456.789.format(4, 4, ' ', ':'); // "12 3456:7890"
Using ECMAScript Internationalization API
There is a newer ECMAScript functionality provided by the Internationalization API.
const formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', minimumFractionDigits: 2 }) // "$1,000.00" formatter.format(1000); // "$10.00" formatter.format(10); // "$1,234,567,890.00" formatter.format(1234567890);
The same can be done for other currencies too.
You can explore it a bit here for the Intl.NumberFormat from Mozilla.