如何将数字格式化为货币字符串 [英] How to format numbers as currency strings
本文介绍了如何将数字格式化为货币字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用JavaScript格式化价格.我想要一个以 float
作为参数并返回格式如下的 string
的函数:
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?
推荐答案
好吧,根据您的说法,我正在使用此代码:
Ok, based on what you said, I'm using this:
var DecimalSeparator = Number("1.2").toLocaleString().substr(1,1);
var AmountWithCommas = Amount.toLocaleString();
var arParts = String(AmountWithCommas).split(DecimalSeparator);
var intPart = arParts[0];
var decPart = (arParts.length > 1 ? arParts[1] : '');
decPart = (decPart + '00').substr(0,2);
return '£ ' + intPart + DecimalSeparator + decPart;
我愿意接受改进建议(我不希望不包含 YUI 就是这样做:-))
I'm open to improvement suggestions (I'd prefer not to include YUI just to do this :-) )
我已经知道我应该检测到.".而不只是将其用作小数点分隔符...
I already know I should be detecting the "." instead of just using it as the decimal separator...
这篇关于如何将数字格式化为货币字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文