Abe Miessler
Abe Miessler

Reputation: 85046

Easy way to convert a string to a number or null?

Is there a slick way to convert a string to a number or null if it cannot be represented by a number? I have been using the method below:

if _.isNaN( Number(mystring)  ) then null else Number(mystring)

Which works, but I'm curious if there is something that is shorter? Possible, or is this the most succinct way?

Upvotes: 0

Views: 514

Answers (2)

Denys Séguret
Denys Séguret

Reputation: 382102

If you don't care for "0", then you can use

+s||null

If you want to support "0", then I don't have better than

1/s?+s:null

Upvotes: 2

Matt
Matt

Reputation: 20776

This is a small improvement to the OP's answer, and is fairly readable:

isNaN(mystring) ? null : +mystring

Upvotes: 0

Related Questions