how to check if a string is a number without isNaN and with conditions

Advertisements

I want to check if a string is a valid number without using isNaN

because I would like to accept the , character that is ignored by isNaN I don’t also want to accept negative numbers and the last condition the number should be between 1 and 99.

example :

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

how can I do this. Thank you very much

>Solution :

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) == 0 ) {
res = false;
}}}
console.log(res)

note that this is accepting ,56 and .76 which are valid. but you can add these condition in the first if statement if you want if(test[0] === '.' || test[0] === ','

Leave a ReplyCancel reply