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
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) {
Number.prototype.toLocaleString = function () {
var n = old.apply(1000);
if (n.length == 8) // IE's implementation, good enough for us
return old.apply(this);
else if (n.length == 5) { // Fx's implementation, needs a little work
return old.apply(this).slice(0,-3) + this.toFixed(2).slice(-3);
} else { // Other implementations
var f = this.toFixed(2).slice(-3);
var s = f.substring(0,1) == "." ? "," : ".";
return this.toFixed(2).slice(0,-3).replace(/(?=(?:\d{3})+(?!\d))/g, s) + f;
}
}
})(Number.prototype.toLocaleString);
Tested in IE, Firefox, Safari, Chrome and Opera in my own locale only (en-GB). It could be shortened down to the last else
block, but I'm a big fan of using native implementations where available, especially when a regex is involved otherwise.
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.