[英]Count the number of digits before and after decimal places using Javascript
[英]vanilla JavaScript solution to check if number has no more than 6 digits and 2 decimal places
如果一个数字的位数不超过6,小数位数不超过2,我需要返回一个验证检查(布尔值)。
例如:
1 = valid
10 = valid
111111 = valid
111111.11 = valid
1111111.11 = INVALID
1.111 = INVALID
通过堆栈溢出,我只能找到自动舍入输入(不是我想要的)或小数位必须等于2个小数位(最多2个)的答案。
显然,您需要
function valid(n) {
return no_more_than_six_digits(n) && no_more_than_two_decimal_places(n);
}
那么我们如何定义这些功能呢?
function no_more_than_six_digits (n) { return n < 1e7; }
function no_more_than_two_decimal_places(n) { return Math.floor(n * 100) === n * 100; }
该功能应该起作用
function t(x) {
return x < 1000000 && Math.floor(x*100)/100 == x;
}
范例http://jsfiddle.net/q6511o17/1/
但请检查torazaburos的答案,以获得更完整的解决方案和解释。
丑陋,但是行得通。
function validate(x) {
return Math.floor(x) < 1000000 &&
(x.toString().indexOf('.') == -1 ?
true : x.toString().split('.')[1].length < 3)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.