使用逗号格式化JavaScript编号 [英] Formatting JavaScript number with commas

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

问题描述

我有一个JavaScript编号,例如 1234.5678 。我试图显示最多四位小数的数据。另外,我想添加相应的逗号。换句话说,我想将之前的数字显示为 1,234.5678 。目前,我有以下内容:

I have a JavaScript Number such as 1234.5678. I am trying to display data up to four decimal places. In addition, I want to add the appropriate commas. In other words, I want to display the previous number as 1,234.5678. Currently, I have the following:

var output = Number(1234.5678).toFixed(4);
output = output.replace(/\B(?=(\d{3})+(?!\d))/g, ",");

这种方法很遗憾地将我的输入值呈现为 1,234.5,678 。小数点右边的逗号是不受欢迎的。但是,我不确定解决此问题的正确方法是什么。似乎应该有一种简单的方法来使用纯JavaScript 格式化数字。请注意,我正在尝试学习JavaScript的细节。出于这个原因,我不是在追求一个库来解决这个问题。相反,我正在尝试更多地了解语言本身。

This approach unfortunately renders my input value as 1,234.5,678. The comma to the right of the decimal place is undesired. However, I'm not sure what the correct way to fix this issue is. It seems like there should be an easy way to format numbers with pure JavaScript. Please note, I am trying to learn the finer points of JavaScript. For that reason, I'm not pursuing a library to solve this problem. Instead, I'm trying to learn more about the language itself.

谢谢!

推荐答案

尝试使用toLocaleString方法

Try to use toLocaleString method

(1234.5678).toLocaleString()
"1,234.568"

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

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