How can I correctly format currency using jquery?

前端 未结 7 1875
故里飘歌
故里飘歌 2020-12-13 01:16

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

7条回答
  •  悲哀的现实
    2020-12-13 02:10

    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.

    $(".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, "$1,").toString());
            });
    

    Simply set the class of whatever input should be formatted as currency and it will format it perfectly in any browser.

提交回复
热议问题