gpt4 book ai didi

javascript - keyup 上的数字在 INR 标准中添加逗号

转载 作者:行者123 更新时间:2023-11-27 23:17:46 25 4
gpt4 key购买 nike

我正在尝试删除输入数字后的文本并添加小数

我有多个input type="text",在按键时我在INR(印度卢比)标准中添加一个逗号,但是当我输入三个以上的数字时,整个值将被删除并且“0” ' 被添加。另外,我的代码不允许使用十进制 .00 数字。我做错了什么?

JS Fiddle

HTML:

<input name="txtMSExMarCardFee" type="number" id="txtMSExMarCardFee" class="Stylednumber">
<input name="txtMSExMarCardFee1" type="number" id="txtMSExMarCardFee1" class="Stylednumber">
<input name="txtMSExMarCardFee2" type="number" id="txtMSExMarCardFee2" class="Stylednumber">

JS:

$('input.Stylednumber').keyup(function(){
var x=$(this).val();
x=x.toString();
var afterPoint = '';
if(x.indexOf('.') > 0)
afterPoint = x.substring(x.indexOf('.'),x.length);
x = Math.floor(x);
x=x.toString();
var lastThree = x.substring(x.length-3);
var otherNumbers = x.substring(0,x.length-3);
if(otherNumbers != '')
lastThree = ',' + lastThree;
var res = otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + lastThree + afterPoint;


$(this).val(res );

});

最佳答案

这要求您在通过正则表达式传递输入之前清理输入

String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.replace(new RegExp(search, 'g'), replacement);
};

$('input.Stylednumber').keyup(function() {
var input = $(this).val().replaceAll(',', '');
if (input.length < 1)
$(this).val('0.00');
else {
var val = parseFloat(input);
var formatted = inrFormat(input);
if (formatted.indexOf('.') > 0) {
var split = formatted.split('.');
formatted = split[0] + '.' + split[1].substring(0, 2);
}
$(this).val(formatted);
}
});

function inrFormat(val) {
var x = val;
x = x.toString();
var afterPoint = '';
if (x.indexOf('.') > 0)
afterPoint = x.substring(x.indexOf('.'), x.length);
x = Math.floor(x);
x = x.toString();
var lastThree = x.substring(x.length - 3);
var otherNumbers = x.substring(0, x.length - 3);
if (otherNumbers != '')
lastThree = ',' + lastThree;
var res = otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + lastThree + afterPoint;
return res;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="txtMSExMarCardFee" type="text" id="txtMSExMarCardFee" class="Stylednumber">
<input name="txtMSExMarCardFee1" type="number" id="txtMSExMarCardFee1" class="Stylednumber">
<input name="txtMSExMarCardFee2" type="number" id="txtMSExMarCardFee2" class="Stylednumber">

关于javascript - keyup 上的数字在 INR 标准中添加逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35680252/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com