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 unknown value is a valid number?

Given a value of type unknown and a configuration describing if that value must be an integer or float value. I started with this function

function isValueNumber(value: unknown, isAcceptingFloatingPointNumbers: boolean) {
  if (Number.isNaN(value)) {
    return false;
  }
  
  if (!isAcceptingFloatingPointNumbers) {
    return Number.isInteger(value);
  }
  
  return true;
}

The problem is that when I call the function like so

isValueNumber("this is not a valid number", true)

it still returns true because my check Number.isNaN is not correct ( Is Number.IsNaN() more broken than isNaN() )

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

Do you have any ideas how to fix this validator function?

>Solution :

This way, the function will return false if not a number :

function isValueNumber(value: unknown, isAcceptingFloatingPointNumbers: boolean) {
  if (typeof value !== 'number') {
    return false;
  }
  
  if (!isAcceptingFloatingPointNumbers) {
    return Number.isInteger(value);
  }
  
  return true;
}

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