简单的方法将字符串转换为数字或null? [英] Easy way to convert a string to a number or null?

查看:200
本文介绍了简单的方法将字符串转换为数字或null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一个光滑的方式将字符串转换为数字或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?

推荐答案

如果你不关心0,那么你可以使用

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

+s||null

$ b b

如果你想支持0,那么我没有

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

1/s?+s:null

这篇关于简单的方法将字符串转换为数字或null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆