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

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

问题描述

我想使用JavaScript格式化数字。

I want to format numbers using JavaScript.

例如:

10     => 10.00
100    => 100.00
1000   => 1,000.00
10000  => 10,000.00
100000 => 100,000.00


推荐答案

如果你想使用内置代码,您可以使用 toLocaleString( ) minimumFractionDigits ,尽管浏览器兼容 toLocaleString()上的扩展选项 受限

If you want to use built-in code, you can use toLocaleString() with minimumFractionDigits, although browser compatibility for the extended options on toLocaleString() is limited.

var n = 100000;
var value = n.toLocaleString(
  undefined, // leave undefined to use the browser's locale,
             // or use a string like 'en-US' to override it.
  { minimumFractionDigits: 2 }
);
console.log(value);
// In en-US, logs '100,000.00'
// In de-DE, logs '100.000,00'
// In hi-IN, logs '1,00,000.00'

如果您使用的是Node.js,则将需要 npm install intl 包。

If you're using Node.js, you will need to npm install the intl package.

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

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