gpt4 book ai didi

javascript - 价格 jquery 中的小数位自动格式

转载 作者:行者123 更新时间:2023-12-03 00:11:10 27 4
gpt4 key购买 nike

我正在尝试隐藏小数位类型输入字段上,例如

数字从0.00开始

因此,输入字段中的第一个位置将为 0.00

我输入的1比它应该变成0.01

我输入的2比它应该变成0.12

0 所以它应该变成 1.20 最后

当我输入0时,它应该变成12.00

0.010.121.2012.00

我尝试了一些SO中已经给出的方法,但没有成功。

如果可能的话,请建议我其他方法。谢谢。

我尝试过这样

$(document).on('keyup','.price',function(e){
var value = $(this).val();
if(value.length <= 6) {
if(e.which == 190 || e.which == 46 || e.which == 44 || e.which == 188){
var amountDots = 0;
var amountCommas = 0;
if(value.indexOf(',') > -1){
amountCommas = value.match(/,/gi).length;
}
if(value.indexOf('.') > -1){
amountDots = value.match(/./gi).length;
}
if((amountDots >= 1 && amountCommas >= 1) || amountCommas > 1 || value.length == 1){
$(this).val(value.substr(0,value.length - 1));
return false;
}
else{
$(this).val(value.substr(0, value.length - 1) + ',');
}
}

$(this).val(value/100); //here is the value will insert

} else {
$(this).val(value.substr(0,value.length - 1))
return false;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="price" />

最佳答案

好的,删除字符时可以使用完全不同的解决方案:

$(document).on('keypress','.price',function(e){
var char = String.fromCharCode(e.which);
if(isNaN(char)) char = '';
var value = $(this).val() + char;
value = value.replace('.','');
$(this).val((value/100).toFixed(2));
if(!isNaN(char)) return false;
}).on('keyup','.price',function(e){
var value = $(this).val();
value = value.replace('.','');
$(this).val((value/100).toFixed(2));
});

https://jsfiddle.net/14shzdo5/

关于javascript - 价格 jquery 中的小数位自动格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54723804/

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