如何使用 jquery 正确格式化货币?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5043650/
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-26 18:25:59  来源:igfitidea点击:

How can I correctly format currency using jquery?

jquerycurrencyformatter

提问by ninjasense

I do not need a mask, but I need something that will format currency(in all browsers) and not allow for any letters or special char's to be typed. Thanks for the help

我不需要掩码,但我需要一些可以格式化货币(在所有浏览器中)并且不允许输入任何字母或特殊字符的东西。谢谢您的帮助

Example:

例子:

Valid: $50.00
$1,000.53

有效:$50.00
$1,000.53

Not Valid: $w45.00
$34.3r6

无效:$w45.00
$34.3r6

采纳答案by Robert Harvey

回答by Melu

Another option (If you are using ASP.Net razor view) is, On your view you can do

另一种选择(如果您使用的是 ASP.Net razor 视图)是,在您的视图中,您可以执行

<div>@String.Format("{0:C}", Model.total)</div>

This would format it correctly. note (item.total is double/decimal)

这将正确格式化它。注意(item.total 是双倍/十进制)

if in jQuery you can also use Regex

如果在 jQuery 中你也可以使用 Regex

$(".totalSum").text('$' + parseFloat(total, 10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, ",").toString());

回答by Chad Kuehn

Expanding upon Melu's answer you can do this to functionalize the code and handle negative amounts.

Sample Output:
$5.23
-$5.23

扩展 Melu 的答案,您可以这样做来功能化代码并处理负数。

样本输出:
$5.23
-$5.23

function formatCurrency(total) {
    var neg = false;
    if(total < 0) {
        neg = true;
        total = Math.abs(total);
    }
    return (neg ? "-$" : '$') + parseFloat(total, 10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, ",").toString();
}

回答by Neptune Systems

As a corollary to why the jQuery FormatCurrency plugin is a good answer, I'd like to rebut your comment:

作为为什么 jQuery FormatCurrency 插件是一个很好的答案的推论,我想反驳您的评论:

1. code.google.com/p/jquery-formatcurrency - Does not filter out all letter's. You can type a single letter and it will not remove it.

1. code.google.com/p/jquery-formatcurrency - 不过滤掉所有字母。您可以键入一个字母,它不会将其删除。

Yes, formatCurrency() by itself does not filter out letters:

是的, formatCurrency() 本身不会过滤掉字母:

// only formats currency
$(selector).formatCurrency();

But toNumber(), included in the formatCurrency plugin, does.

但是包含在 formatCurrency 插件中的 toNumber() 可以。

You thus want to do:

因此,您想要执行以下操作:

// removes invalid characters, then formats currency
$(selector).toNumber().formatCurrency();

回答by Fernando Kosh

Use jquery.inputmask 3.x. See demos here

使用jquery.inputmask 3.x在此处查看演示

Include files:

包含文件:

<script src="/assets/jquery.inputmask.js" type="text/javascript"></script>
<script src="/assets/jquery.inputmask.extensions.js" type="text/javascript"></script>
<script src="/assets/jquery.inputmask.numeric.extensions.js" type="text/javascript"></script>

And code as

并编码为

$(selector).inputmask('decimal',
  { 'alias': 'numeric',
    'groupSeparator': '.',
    'autoGroup': true,
    'digits': 2,
    'radixPoint': ",",
    'digitsOptional': false,
    'allowMinus': false,
    'prefix': '$ ',
    'placeholder': '0'
  }
);

Highlights:

强调:

  • easy to use
  • optional parts anywere in the mask
  • possibility to define aliases which hide complexity
  • date / datetime masks
  • numeric masks
  • lots of callbacks
  • non-greedy masks
  • many features can be enabled/disabled/configured by options
  • supports readonly/disabled/dir="rtl" attributes
  • support data-inputmask attribute(s)
  • multi-mask support
  • regex-mask support
  • dynamic-mask support
  • preprocessing-mask support
  • value formatting / validating without input element
  • 便于使用
  • 面罩中的任何可选零件
  • 定义隐藏复杂性的别名的可能性
  • 日期/日期时间掩码
  • 数字掩码
  • 大量回调
  • 非贪婪面具
  • 许多功能可以通过选项启用/禁用/配置
  • 支持 readonly/disabled/dir="rtl" 属性
  • 支持数据输入掩码属性
  • 多面罩支持
  • 正则表达式掩码支持
  • 动态掩码支持
  • 预处理掩码支持
  • 没有输入元素的值格式化/验证

回答by Greg Snider

I used to use the jquery format currency plugin, but it has been very buggy recently. I only need formatting for USD/CAD, so I wrote my own automatic formatting.

以前用的是jquery格式的货币插件,但是最近bug很多。我只需要格式化美元/加元,所以我编写了自己的自动格式。

$(".currencyMask").change(function () {
            if (!$.isNumeric($(this).val()))
                $(this).val('0').trigger('change');

            $(this).val(parseFloat($(this).val(), 10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, ",").toString());
        });

Simply set the class of whatever input should be formatted as currency <input type="text" class="currencyMask" />and it will format it perfectly in any browser.

只需将任何输入的类别设置为货币<input type="text" class="currencyMask" />,它就会在任何浏览器中完美地格式化。

回答by KingRider

Try regexp currency with jQuery (no plugin):

使用 jQuery 尝试正则表达式货币(无插件)

$(document).ready(function(){
  $('#test').click(function() {
    TESTCURRENCY = $('#value').val().toString().match(/(?=[\s\d])(?:\s\.|\d+(?:[.]\d+)*)/gmi);
    if (TESTCURRENCY.length <= 1) {
      $('#valueshow').val(
        parseFloat(TESTCURRENCY.toString().match(/^\d+(?:\.\d{0,2})?/))
      );
    } else {
      $('#valueshow').val('Invalid a value!');
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" value="12345.67890" id="value">
<input type="button" id="test" value="CLICK">
<input type="text" value="" id="valueshow">

Edit: New check a value to valid/invalid

编辑:新检查一个值是否有效/无效