香草JavaScript解决方案来检查数字是否不超过6位和2位小数

vanilla JavaScript solution to check if number has no more than 6 digits and 2 decimal places

本文关键字:6位 不超过 2位 小数 是否 数字 JavaScript 解决方案 检查 香草      更新时间:2023-09-26

我需要返回一个验证检查(布尔值),如果一个数字有不超过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)
}