JavaScript 中的货币格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14467433/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 16:52:48  来源:igfitidea点击:

Currency Formatting in JavaScript

javascriptjquery

提问by kevg

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

可能的重复:
如何在 JavaScript 中将数字格式化为货币?

I have a form with some simple JavaScript to perform an instant calculation. My problem is that I'm struggling to format it to display correctly with commas and 2 decimal places.

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

Any help would be very much appreciated. Thank you.

任何帮助将不胜感激。谢谢你。

    <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>

回答by Tom

You can use standard JS toFixedmethod

您可以使用标准的 JStoFixed方法

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

//5.57

In order to add commas (to separate 1000's) you can add regexp as follows (where numis a number):

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

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

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

Complete example:

完整示例:

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

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

Separation character depends on country and locale. For some countries it may need to be .

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

回答by Harish

You could use toPrecision() and toFixed() methods of Number type. Check this link How can I format numbers as money in JavaScript?

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