Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting number in European format with two decimals

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/

like image 391
anmatika Avatar asked Jun 11 '15 09:06

anmatika


People also ask

How are decimals written in Europe?

Europe. The majority of European countries use the decimal comma. Among them are Spain, France, Norway, the Czech Republic, Denmark, and more. However, it's important to note that the United Kingdom is an exception because they tend to follow the Imperial System, which uses the decimal point.

How are numbers formatted in Europe?

In most European countries, a comma is used to separate the integral part of a number from the decimal part. This means, for example, that three hundred euros and ten cents is written as 300,10—with a comma as a decimal marker.

How can I format a decimal to always show 2 decimal places?

1. DecimalFormat(“0.00”) We can use DecimalFormat("0.00") to ensure the number is round to 2 decimal places.

Do Europeans use commas as decimals?

Currently, in European countries except for the United Kingdom, the comma is used as the decimal separator. In the United Kingdom, the raised dot is used, and in the United States, the baseline dot is used.


1 Answers

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.

like image 56
Álvaro González Avatar answered Sep 25 '22 01:09

Álvaro González