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

随声附和 提交于 2019-12-25 02:03:21

问题


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?


回答1:


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



回答2:


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

isNaN(mystring) ? null : +mystring


来源:https://stackoverflow.com/questions/21636913/easy-way-to-convert-a-string-to-a-number-or-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!