我想在不使用isNaN的情况下检查字符串是否为有效数字
因为我想接受被isNaN忽略的,
字符,我也不想接受负数,最后一个条件是数字应该在1到99之间。
的例子:
let a = '--5'; // false
let b = '95.5'; // true it can accept . also
let c = '99,8'; // false bigger than 99
let d = '99,'; // false
我怎么能做到这一点。非常感谢
const test = '55.'
var res = true;
if(test[0] === '-' || test[test.length-1] === ',' || test[test.length-1] === '.'){
res = false;
}else{
let final = test.replace(/,/g, ".");
if(isNaN(final)){
res = false;
}else{
if(Number(final)>99 ||Number(final) < 1 ) {
res = false;
}}}
console.log(res)
注意这是接受有效的,56
和.76
。但如果你想要if(test[0] === '.' || test[0] === ','
a = '-5';
a = a.replace(/,/g, '.');
//check a is number
if (isNaN(a) || a.startsWith('-') ) {
console.log('not a number');
}else{
console.log(' not a number');
if(a > 0 && a < 100){
console.log(' a number');
}
}