.NET decimal.ToString(format) in Javascript

我怕爱的太早我们不能终老 提交于 2019-12-24 00:44:02

问题


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


回答1:


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).




回答2:


I think jQuery Globalization plugin gets close




回答3:


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.



来源:https://stackoverflow.com/questions/3044056/net-decimal-tostringformat-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!