0

In JavaScript, I have an arbitrary number as input.
For example:

var number = parseFloat(12345678901234.1234567);

Now I want to display it as:

12'345'678'901'234.12

it should be

xxx'xxx'xxx.00 

if it is an integer, and

xxx'xxx'xxx.y0 

if only one digit after the decimal point

I would have assumed that this would do the trick:

var number = parseFloat(12345678901234.1234567);

console.log(number.toLocaleString('de-CH', { minimumFractionDigits:2, maximumFractionDigits: 2

}));

But it actually displayed 12'345'678'901'234.10 instead of 12'345'678'901'234.12

So I thought maybe I need to set minimumSignificantDigits to 2, too.
But bad luck, I discovered minimumSignificantDigits apparently considers all the digits in the string, for whatever idiotic reason, so I need to add the number of digits of the integer part to 2. Like:

var number = parseFloat(12345678901234.1234567);


console.log(number.toLocaleString('de-CH', { minimumFractionDigits:2, maximumFractionDigits: 2

,minimumSignificantDigits: parseInt(number).toString().length + 2
}));

But this still displays

12'345'678'901'234.10

Converting the float to the Number type doesn't help either, the output is still the same.

var number = Number(parseFloat(12345678901234.1234567));

console.log(number.toLocaleString('de-CH', { minimumFractionDigits:2, maximumFractionDigits: 2

,minimumSignificantDigits: parseInt(number).toString().length + 2
}));

I also tried this

var number = parseFloat(12345678901234.1234567);
number.toLocaleString('de-CH', {style: 'currency', currency: 'CHF', currencyDisplay: 'code'}).replace('CHF', '')

but it does not seem to work either.
Adding style: "decimal" doesn't help, either...
Additionally, I don't want to have to know the currency name for each locale.

What am I doing wrong ?
Is there really no other way than writing my own formatting code (where I have the problem that I don't know the thousand separator char for each locale) ? Or is this a JavaScript bug for certain ?

  • Yep, sorry I re-read the question & removed the comment :) – CodingIntrigue Apr 08 '16 at 08:08
  • 1
    @RGraham: No problem. Removed mine, too. But thanks for the indirect link to https://github.com/dtrebbien/BigDecimal.js , that's very interesting. –  Apr 08 '16 at 08:34
  • Possible duplicate of [JavaScript: Format whole numbers using toLocaleString()](http://stackoverflow.com/questions/21536984/javascript-format-whole-numbers-using-tolocalestring) – Paul Sweatte Dec 23 '16 at 16:22

0 Answers0