.NET Decimal.ToString的(格式)在Javascript格式、Decimal、NET、Javascript

2023-09-06 14:39:35 作者:心如刀割。

我有一个字符串(€#,###。00),它工作正常aDecimal.ToString(€#,###。00)在.NET中,我不知道是否有人知道如何可以实现用JavaScript

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

推荐答案

还有 .toLocaleString(),但不幸的是规范这个定义为实现相关的 - 我讨厌当他们做到这一点。因此,它的行为不同的方式在不同的浏览器:

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()!)

所以,你可以看到它不能在因为ECMA队都懒得正确地定义它依赖。而Internet Explorer不是它格式化为货币的最好的工作。你最好用自己的或别人的实现。 或矿的:

(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);

经过测试,在IE,火狐,Safari,Chrome和Opera在我自己的语言环境只(EN-GB)。

Tested in IE, Firefox, Safari, Chrome and Opera in my own locale only (en-GB).