Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 138221

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

$
0
0

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.


Viewing all articles
Browse latest Browse all 138221

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>