如何在JavaScript中将数字格式设置为美元货币字符串?

编程入门 行业动态 更新时间:2024-10-25 04:18:20
本文介绍了如何在JavaScript中将数字格式设置为美元货币字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想用JavaScript格式化一个价格。 我想要一个以 float 作为参数的函数,并返回一个

执行此操作的最佳方法是什么?

解决方案

var profits = 2489.8237 profit.toFixed(3)/ /返回2489.824(凑整) profit.toFixed(2)//返回2489.82 profit.toFixed(7)//返回2489.8237000(填充)

然后您可以添加'$'的符号。

如果您需要','您可以使用的数千元: $ p $ Number.prototype.formatMoney = function(c,d,t){ var n = this,c = isNaN(c = Math.abs(c))? 2:c, d = d == undefined? :d, t = t == undefined? ,:t, s = n < 0? - :i = String(parseInt(n = Math.abs(Number(n)|| 0).toFixed(c))),j =(j = i.length) > 3? j%3:0; return s +(j?i.substr(0,j)+ t:)+ i.substr(j).replace(/(\d {3})(?= \ d) / g,$ 1+ t)+(c?d + Math.abs(n-i).toFixed(c).slice(2):); };

和它一起使用: <$ p $ (123456789.12345).formatMoney(2,'。',',');

如果您总是使用'​​。'和',',您可以将它们关闭你的方法调用,方法会默认为你。

(123456789.12345).formatMoney(2);

如果您的文化有两个符号翻转(即欧洲人),只需粘贴以下两行 formatMoney 方法:

d = d == undefined? ,:d, t = t == undefined? :t,

I would like to format a price in JavaScript. I'd like a function which takes a float as an argument and returns a string formatted like this:

"$ 2,500.00"

What's the best way to do this?

解决方案

You can use:

var profits=2489.8237 profits.toFixed(3) //returns 2489.824 (round up) profits.toFixed(2) //returns 2489.82 profits.toFixed(7) //returns 2489.8237000 (padding)

Then you can add the sign of '$'.

If you require ',' for thousand you can use:

Number.prototype.formatMoney = function(c, d, t){ var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "." : d, t = t == undefined ? "," : t, s = n < 0 ? "-" : "", i = String(parseInt(n = Math.abs(Number(n) || 0).toFixed(c))), j = (j = i.length) > 3 ? j % 3 : 0; return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ""); };

And use it with:

(123456789.12345).formatMoney(2, '.', ',');

If you're always going to use '.' and ',', you can leave them off your method call, and the method will default them for you.

(123456789.12345).formatMoney(2);

If your culture has the two symbols flipped (i.e. Europeans), just paste over the following two lines in the formatMoney method:

d = d == undefined ? "," : d, t = t == undefined ? "." : t,

更多推荐

如何在JavaScript中将数字格式设置为美元货币字符串?

本文发布于:2023-10-22 22:25:57,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:设置为   字符串   中将   货币   美元

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!