检查文本是否只有十进制数字



是否有最有效的方法来验证JavaScript中的十进制数?

例如:

01. IsDec('-7.7')      => true
02. IsDec('-18')    => true
03. IsDec('0')       => true
04. IsDec('.845')    => true
05. IsDec('0.957')     => true
06. IsDec('0x45f')  => false
07. IsDec('15,87')   => false
08. IsDec('#text') => false
09. IsDec('75.95.69')   => false
10. IsDec('')        => false
11. IsDec('someText')    => false

这样尝试:

console.log(isDec("-12.5"));
console.log(isDec("12.5"));
console.log(isDec("0"));
console.log(isDec(".45"));
console.log(isDec("1,5"));
console.log(isDec("#ssdr"));
function isDec(txt) {
return !isNaN(parseFloat(txt)) && isFinite(txt);
}

这里有一个用于检查的正则表达式。

/^-?d*.?d*(?<!^.?)$/

console.log('--- true cases ---');
console.log(isDec('-7.7'));
console.log(isDec('-18'));
console.log(isDec('0'));
console.log(isDec('.845'));
console.log(isDec('0.957'));
console.log(isDec('16.'));
console.log('--- false cases ---');
console.log(isDec('0x45f'));
console.log(isDec('15,87'));
console.log(isDec('#text'));
console.log(isDec('75.95.69'));
console.log(isDec(''));
console.log(isDec('someText'));
console.log(isDec('.'));
function isDec(txt) {
const regex = /^-?d*.?d*(?<!^.?)$/;
return regex.test(txt);
}

点击此处查看结果

请尝试以下函数检查十进制数

function isDecimal(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}

ans:

isDecimal('-7.7')      => true

相关内容

  • 没有找到相关文章