Trying to format a number to two decimals format in European culture. So that comma is decimal separator and space thousands separator.
In example 213245 should be formatted as 213 245,00
How can I do that?
213245.toFixed(2).toLocaleString();
gives 213245.00 but it should be 213 245,00
however
213245.toLocaleString()
gives 213 245
Fiddling below:
var out, input;
input = 213245;
// TEST 1
out = input.toFixed(2);
console.log(out); // 213245.00
out = out.toLocaleString();
console.log(out); // 213245.00
// TEST 2
out = input.toLocaleString();
console.log(out); // 213 245
When you use Number.toFixed() you obtain a string (not a number any more). For that reason, subsequent calls to
.toLocaleString()
launch the generic Object.toLocaleString() method that knows nothing about numbers, instead of the Number.toLocaleString() you want.Having a look at the documentation we can compose something like this:
This is a relatively new addition so make sure to verify browser support, but it's been working in Firefox and Chrome-like browsers for a few years now. In particular, some runtimes like Node.js do not include the full ICU dataset by default.