如何使用JavaScript格式化数字? [英] How to format numbers using JavaScript?

查看:169
本文介绍了如何使用JavaScript格式化数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用javascript格式化数字如下:

I want to format number using javascript as below:

10.00=10,00 
1,000.00=1.000,00


推荐答案

每个浏览器都支持 Number .prototype.toLocaleString(),一种用于从数字返回本地化字符串的方法。但是,规范将其定义如下:

Every browser supports Number.prototype.toLocaleString(), a method intended to return a localized string from a number. However, the specification defines it as follows:


生成一个字符串值,表示根据主机约定格式化的Number的值环境的当前区域设置。此函数是依赖于实现的,允许但不鼓励它返回与 toString 相同的内容。

Produces a string value that represents the value of the Number formatted according to the conventions of the host environment's current locale. This function is implementation-dependent, and it is permissible, but not encouraged, for it to return the same thing as toString.

依赖于实现意味着由供应商决定结果的外观,并导致互操作性问题。

Implementation-dependant means that it's up to the vendor how the result will look, and results in interoperability issues.

Internet Explorer (IE 5.5到IE 9)最接近您想要的格式并以货币样式格式化数字 - 千位分隔符并固定为2位小数。

Internet Explorer (IE 5.5 to IE 9) comes closest to what you want and formats the number in a currency style - thousands separator and fixed at 2 decimal places.

Firefox (2+)将数字格式化为千位分隔符和小数位,但仅在适用的情况下。

Firefox (2+) formats the number with a thousands separator and decimal places but only if applicable.

Opera,Chrome& Safari 输出与 toString()相同 - 仅在需要时没有千位分隔符,小数位。


Opera, Chrome & Safari output the same as toString() -- no thousands separator, decimal place only if required.

我想出了以下代码(基于我的一个老答案)尝试将结果标准化为Internet Explorer的方法:

I came up with the following code (based on an old answer of mine) to try and normalize the results to work like Internet Explorer's method:

(function (old) {
    var dec = 0.12 .toLocaleString().charAt(1),
        tho = dec === "." ? "," : ".";

    if (1000 .toLocaleString() !== "1,000.00") {
        Number.prototype.toLocaleString = function () {
           var neg = this < 0,
               f = this.toFixed(2).slice(+neg);

           return (neg ? "-" : "") 
                  + f.slice(0,-3).replace(/(?=(?!^)(?:\d{3})+(?!\d))/g, tho) 
                  + dec + f.slice(-2);
        }
    }
})(Number.prototype.toLocaleString);

这将使用浏览器的内置本地化(如果可用),同时优雅降级到浏览器的默认语言环境在其他情况下。

This will use the browser's built-in localization if it's available, whilst gracefully degrading to the browser's default locale in other cases.

工作演示: http://jsfiddle.net/R4DKn/49/

这篇关于如何使用JavaScript格式化数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆