Miguel Moura
Miguel Moura

Reputation: 39404

Convert String to Number. Must always be NaN if conversion fails

The following String to Number conversion, in Typescript, returns the results:

console.log(+'20'); > 20
console.log(+'A');  > NaN
console.log(+' ');  > 0
console.log(+'');   > 0

How to make sure that any string with invalid number returns NaN and not 0.

I would need the last two to return NaN not the default number value.

Update

Following some suggestion I tried:

console.log('20.35'.trim() == '' ? NaN : +('20.35'.trim()));    > 20.35

console.log('20'.trim() == '' ? NaN : +('20'.trim()));          > 20

console.log('-1.75 '.trim() == '' ? NaN : +('-1.75 '.trim()));  > -1.75

console.log(''.trim() == '' ? NaN : +(''.trim()));              > NaN

console.log('   '.trim() == '' ? NaN : +('   '.trim()));        > NaN

This works as expected. Not sure if it is the best option or if I am missing something out.

Upvotes: 1

Views: 3381

Answers (2)

Tom Dezentje
Tom Dezentje

Reputation: 631

You can use parseInt(i) or parseFloat(i). See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

parseInt('10') === 10;
parseInt('A') === NaN;
parseInt(' ') === NaN;
parseInt('') === NaN;
parseFloat('10.20') === 10.2;
parseFloat('10') === 10;

Upvotes: 2

Sachin Shah
Sachin Shah

Reputation: 4533

Try this way

+'' == 0 ? NaN : 1   -> return NaN

+ ' ' ? NaN : 1       -> return 1 

Upvotes: 0

Related Questions