使用jQuery / JS键入时,使用1000个分隔符和2个小数位格式化货币输入? [英] Format currency input with 1000 separator and 2 decimal places upon typing using jQuery/JS?

查看:100
本文介绍了使用jQuery / JS键入时,使用1000个分隔符和2个小数位格式化货币输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本输入,我希望它在键入一个允许2个小数位和1000个分隔符的值时进行格式化。它应该只允许数字。
我已完成以下操作,但不允许添加小数点。简单地说就是输入产品的价格(货币)。

I have a text input where I want it to format while typing a value allowing 2 decimal places and 1000 separators. It should only allow digits. I have done the following but it does not allow adding decimal points. Simply put it is for entering the price of a product (currency).


INPUT = 1234560ABC.5665(应该只允许数字)

INPUT = 1234560ABC.5665 (should only allow numbers)

EXPECTED = 1,234,560.56(应将小数位数限制为2)

EXPECTED = 1,234,560.56 (should limit decimal places to 2)

我做过以下但不知道如何添加小数值后跟。保护,1000分隔符。

I have done the following but no idea how to add decimal values followed by a "." securing the "," 1000 separators.

<input type="text" id="price" name="price" />

$('#price').keyup(function (event) {
    $(this).val(function (index, value) {
        return '$' + value.replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    });
});


推荐答案

$('#price').on('keyup click change paste input', function (event) {
    $(this).val(function (index, value) {
        if (value != "") {
            //return '$' + value.replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
            var decimalCount;
            value.match(/\./g) === null ? decimalCount = 0 : decimalCount = value.match(/\./g);

            if (decimalCount.length > 1) {
                value = value.slice(0, -1);
            }

            var components = value.toString().split(".");
            if (components.length === 1)
                components[0] = value;
            components[0] = components[0].replace(/\D/g, '').replace(/\B(?=(\d{3})+(?!\d))/g, ',');
            if (components.length === 2) {
                components[1] = components[1].replace(/\D/g, '').replace(/^\d{3}$/, '');
            }

            if (components.join('.') != '')
                return '$' + components.join('.');
            else
                return '';
        }
    });
});

这篇关于使用jQuery / JS键入时,使用1000个分隔符和2个小数位格式化货币输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆