Home  >  Article  >  Web Front-end  >  JS retains two decimal places for input number verification code

JS retains two decimal places for input number verification code

php中世界最好的语言
php中世界最好的语言Original
2018-05-11 15:11:282400browse

This time I will bring you the JS retaining two decimal places input number verification code, JS retaining two decimal places input number verification What are the precautions, the following is a practical case, let's take a look .

Input input format verification:

$(function(){
var data = $.trim($("#inputId").val());
//此正则表达式验证小数位是否超过两位,小数可为1位 || 2位 || 整数
if(!(/^\d+(\.\d{1,2})?$/.test(data ) || /^\d$/.test(data ) )){
alert("输入金额格式不对!最高精确到分");
return ;
}
//写入对应位置
$(".htmlTextClass").innerText(toDecimal2(data ));
});
//强制小数位保留方法
function toDecimal2(x) {
var f = parseFloat(x);
//isNaN() 函数用于检查其参数是否是非数字值,如果 x 是特殊的非数字值 NaN(或者能被转换为这样的值),返回的值就是 true。如果 x 是其他值,则返回 false。
if (isNaN(f)) {
return false;
}
var f = Math.round(x*100)/100; //round() 方法可把一个数字舍入为最接近的整数
var s = f.toString();
var rs = s.indexOf('.');
if (rs < 0) {
rs = s.length;
s += '.';
}
while (s.length <= rs + 2) {
s += '0';
}
return s;
}

Supplement: Let’s look at the solution to retain two decimal places in js

var a = 123.456;
a = a..toFixed(2);
alert(a);//结果:123.46

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

vue environment passing parameters packaging different domain name code analysis

How Vue operates html field string conversion For HTML tags

The above is the detailed content of JS retains two decimal places for input number verification code. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn