Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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] === ','

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading