40

Do you know if toFixed is a localized function?

I mean, will this:

var n = 100.67287;
alert(n.toFixed(2));

show "100.67" on English US OS/browsers and "100,67" (with comma) on Italian OS/browsers? (Italian or any other local system that uses comma as decimal separator).

2

4 Answers 4

51

Late addition: with Number.toLocaleString() now available on everything bar IE 10 & below, this works, albeit rather long-winded:

var n = 100.67287;
console.log(n.toLocaleString(undefined, {
  minimumFractionDigits: 2,
  maximumFractionDigits: 2
}));

Using undefined or 'default' for the language code will use the browser default language to format the number.

See developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString for full details.

If you're free to extend the Number prototype, you could defined Number.toLocaleFixed().

Sign up to request clarification or add additional context in comments.

3 Comments

Long-winded as it may be, it's the best solution I've seen so far.
Or simply n.toFixed(2).toLocaleString()
@dataman That’s different: Number.prototype.toLocaleString will format the decimal point according to the locale, e.g. "100,67287" instead of "100.67287". toFixed circumvents this and always uses a .. Your suggestion would use String.prototype.toLocaleString, and it is no longer aware of the numeric properties of n.
29

No, this will always return a point. The ECMA 262-spec [15.7.4.5] states it should be a point.

1 Comment

This link is broken and there are "too many pending edits", so here's an updated link: ecma-international.org/publications-and-standards/standards/…
1

You can use this:

var n = 100.67287;
alert(parseFloat(n.toFixed(2)).toLocaleString());

On my german system the result is

100,67

2 Comments

This is a clever hack, but won't work correctly for 100.00, which will result in "100" via toLocaleString()
For display purposes - skip the parseFloat and leave as a string.
-2

No sadly, there is no real solution in pure jQuery/JavaScript. You'll need Globalize. The problem is that both toFixed() and toLocaleString() take a number and return a string. So you can never use them together. :( If you call foo.toFixed(2).toLocaleString() you won't get the localization (i.e. '1.234' in en should be '1,234' in fr) because its working on the result of toFixed() which is a string, not a number. :(

1 Comment

Support for the ECMA-402 Internationalization API has been specified since ECMAScript 2015 (ed. 6), so this answer is no longer current as Number.prototype.toLocaleString can specify both language specific formatting and number of decimal places per ChrisV's answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.