JavaScript中的货币格式

时间:2013-01-22 20:29:32

标签: javascript jquery

  

可能重复:
  How can I format numbers as money in JavaScript?

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

非常感谢任何帮助。谢谢。

    <p>
    <label>My Daily Rate is:</label><br />
<input class="poundsBox" name="shares" id="shares" type="text" /><br />
<br />
<strong>Your Gross Contract Take Home:</strong></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);
})
</script>

2 个答案:

答案 0 :(得分:104)

您可以使用标准JS toFixed方法

var num = 5.56789;
var n=num.toFixed(2);

//5.57

为了添加逗号(分隔1000个),你可以按如下方式添加正则表达式(其中num是一个数字):

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

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

完整示例:

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

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

答案 1 :(得分:2)

您可以使用Number类型的toPrecision()和toFixed()方法。请检查此链接How can I format numbers as money in JavaScript?