Home > Web Front-end > JS Tutorial > body text

Detailed explanation of JS mandatory retention of two decimal places for input verification steps

php中世界最好的语言
Release: 2018-05-22 14:13:23
Original
1791 people have browsed it

This time I will bring you a detailed explanation of the steps for JS to force the retention of two decimal places for input verification. What are the precautions for JS to force retention of two decimal places for input verification? The following is a practical case, let’s take a look one time.

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;
}
Copy after login

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
Copy after login

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:

js regular related use case sharing

How to handle repeated submission of data when the vue button is clicked multiple times

The above is the detailed content of Detailed explanation of JS mandatory retention of two decimal places for input verification steps. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!