Reputation: 39404
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
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
Reputation: 4533
Try this way
+'' == 0 ? NaN : 1 -> return NaN
+ ' ' ? NaN : 1 -> return 1
Upvotes: 0