简体   繁体   中英

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.

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;

Try this way

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

+ ' ' ? NaN : 1       -> return 1 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM