I have a string (€#,###.00) which works fine with aDecimal.ToString("€#,###.00") in .NET, i wonder if anyone knows how this could be achieved with javascript
3 Answers
There's .toLocaleString()
, but unfortunately the specification defines this as "implementation dependant" - I hate when they do that. Thus, it behaves differently in different browsers:
var val = 1000000;
alert(val.toLocaleString())
// -> IE: "1,000,000.00"
// -> Firefox: "1,000,000"
// -> Chrome, Opera, Safari: "1000000" (i know, it's the same as toString()!)
So you can see it can't be relied upon because the ECMA team were too lazy to properly define it. Internet Explorer does the best job of formatting it as a currency. You're better off with your own or someone else's implementation.
or mine:
(function (old) {
var dec = 0.12 .toLocaleString().charAt(1),
tho = dec === "." ? "," : ".";
if (1000 .toLocaleString() !== "1,000.00") {
Number.prototype.toLocaleString = function () {
var f = this.toFixed(2).slice(-2);
return this.toFixed(2).slice(0,-3).replace(/(?=(?!^)(?:\d{3})+(?!\d))/g, tho) + dec + f;
}
}
})(Number.prototype.toLocaleString);
Tested in IE, Firefox, Safari, Chrome and Opera in my own locale only (en-GB).

- 338,112
- 86
- 474
- 445
-
Thanks, but yea doesn't help much :p – Mikael Gidmark Jun 15 '10 at 10:46
-
@Mikael: you're right, it wasn't very helpful. I added my own solution to the post, tested in Firefox, IE, Opera, Chrome and Safari. – Andy E Jun 15 '10 at 11:11
I think jQuery Globalization plugin gets close

- 52,015
- 16
- 101
- 139
-
yea im using that for when i have a locale, but in some cases i don't and i only have that formatting string – Mikael Gidmark Jun 15 '10 at 09:56
-
And what would output would you expect from the formatting string without the locale? – GvS Jun 15 '10 at 10:00
-
well in this case i have Euro, it's hard to tie Euro to a single locale, that's why i want to be able to specify a format for the currency Euro, inputting 1200.5 with the format €#,###.00 should obviously output €1,200.50 I guess i have to attempt to write my own function since it doesn't seem to exist. – Mikael Gidmark Jun 15 '10 at 10:45
-
-
Yea that's what i have atm, the problem is just that it might be other custom formats in the future. But i guess ill have to deal with them later. – Mikael Gidmark Jun 15 '10 at 12:14
I had the same Problem once and I decided to go with a little overengineered (maybe stupid) way: I wrote a service who accepted a decimal as parameter and gave me a formatted string back. The main Problem was, that I didnt know which culture the User was using in Javascript.

- 3,132
- 3
- 25
- 31
-
in my case it'd be too much to do ajax calls for every format instance – Mikael Gidmark Jun 15 '10 at 10:46