Formatting number in European format with two decimals

25.4k Views Asked by At

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

https://jsfiddle.net/rootnode/8p2vad8u/7/

1

There are 1 best solutions below

0
On BEST ANSWER

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:

> Number(213245).toLocaleString("es-ES", {minimumFractionDigits: 2});
"213.245,00"

console.log(Number(213245).toLocaleString("es-ES", {minimumFractionDigits: 2}));

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.