本文介绍了使用javascript或jquery只允许2个小数点输入到文本框吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为我的文本框调用了一个名为test的类.当我输入第一个值时第一个值为4.,然后突然输出为4.00.我只想只允许输入两位小数.

I called a class called test for my textbox. When I entered the first value for e.g. the first value as 4., then suddenly the output coming as 4.00. I just want to restrict entry only for two decimal places.

$(".test").keyup(function (event) {
    debugger;
    this.value = parseFloat(this.value).toFixed(2);
});

推荐答案

对您的代码进行的微小更改就足够了:

This small change to your code may suffice:

  this.value = this.value.replace (/(\.\d\d)\d+|([\d.]*)[^\d.]/, '$1$2');

基本上用小数点代替小数点,然后用小数点和仅前两位代替任何数字.或者,如果输入了非数字,则将其删除.

Essentially replace the decimal point followed by any number of digits by a decimal point and the first two digits only. Or if a non digit is entered removes it.

这篇关于使用javascript或jquery只允许2个小数点输入到文本框吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 20:32