关于jquery:JavaScript中的货币格式

Currency Formatting in JavaScript

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
How can I format numbers as money in JavaScript?

我有一个带有简单javascript的表单来执行即时计算。我的问题是,我正在努力格式化它,以便它能正确显示逗号和2位小数。

任何帮助都将不胜感激。谢谢您。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
    <p>

    <label>My Daily Rate is:</label><br />
<input class="poundsBox" name="shares" id="shares" type="text" /><br />
<br />
Your Gross Contract Take Home:
</p>
<p>
<span class="result">&pound; <span id="result"></span></span>
</p>
The above illustration is provided for guidance only. Please complete the request form below for a detailed personal illustration.

<script type="text/javascript">
$("#shares").keyup(function() {
   var val = parseFloat($(this).val());
   // If val is a good float, multiply by 260, else show an error
   val = (val ? val * 260 * 0.88 :"Invalid number");
   $("#result").text(val);
})


可以使用标准JS toFixed方法

1
2
3
4
var num = 5.56789;
var n=num.toFixed(2);

//5.57

为了添加逗号(分开1000个),可以按如下方式添加regexp(其中num是一个数字):

1
2
3
4
5
num.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1,")

//100000 => 100,000
//8000 => 8,000
//1000000 => 1,000,000

完整示例:

1
2
3
4
var value = 1250.223;
var num = '$' + value.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1,");

//document.write(num) would write value as follows: $1,250.22

分隔符取决于国家和地区。对于某些国家,可能需要是.


可以使用数字类型的topRecision()和toFixed()方法。检查此链接我如何在javascript中将数字格式化为货币?