javascript中带逗号和2位小数的正则表达式格式字符串编号 [英] regex format string number with commas and 2 decimals in javascript

查看:38
本文介绍了javascript中带逗号和2位小数的正则表达式格式字符串编号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串 n,它是一个数字.下面在需要的地方添加逗号,但我也想更改小数位数.它还应该在适当的地方取整.

I have a string n which is a number. The following adds the commas where needed, but I also want to change the number of decimals. It should also round where appropriate.

var parts = n.split(".");
var num = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (parts[1] ? "." + parts[1] : "");

这会将 1234.567 之类的数字转换为 1,234.567.但我需要我的号码看起来像:1,234.57

This turns a number like 1234.567 in to 1,234.567. But I need my number to look like: 1,234.57

我尝试将 parts[1] 转换为数字,然后四舍五入,然后将其连接回来;但这很容易出错.

I tried taking parts[1] and converting to a Number, then rounding, then concatenating it back; but that is error prone.

我怎样才能通过改变我的正则表达式来得到这个结果?谢谢.

How can I get this result by altering my regex? Thanks.

推荐答案

var val = Math.round(Number(n) *100) / 100;
var parts = val.toString().split(".");
var num = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (parts[1] ? "." + parts[1] : "");

这篇关于javascript中带逗号和2位小数的正则表达式格式字符串编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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