将字符串转换为javascript中的数字 [英] convert string to a number in javascript

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

问题描述

我想解析包含经度和纬度的用户输入。我想要做的是将字符串强制转换为数字,保留其符号和小数位。但我想要做的是在用户输入无效时显示消息。我应该关注哪一个

I want to parse a user input which contains longitude and latitude. What I want to do is to coerce a string to a number, preserving its sign and decimal places. But what I want to do is to display a message when user's input is invalid. Which one should I follow

parseFloat(x)

new Number(x)

第三

~~x

第四

+x


推荐答案

我用 Number(x),如果我必须在这两者之间做出选择,因为它不允许尾随垃圾。 (好吧,它允许它,但结果是 NaN 。)

I'd use Number(x), if I had to choose between those two, because it won't allow trailing garbage. (Well, it "allows" it, but the result is a NaN.)

数字(123.45balloon) NaN ,但是 parseFloat(123.45balloon) 123.45 (作为数字)。

That is, Number("123.45balloon") is NaN, but parseFloat("123.45balloon") is 123.45 (as a number).

正如Kling先生指出的那样,那些更好取决于你。

As Mr. Kling points out, which of those is "better" is up to you.

编辑—啊,你已经加回了 + x ~~ x 。正如我在评论中写的那样, + x 相当于使用 Number()构造函数,但我认为这是一个由于 + 运算符的语法灵活性,风险很小。也就是说,剪切和粘贴很容易引入错误。如果你知道你想要一个整数(一个32位整数), ~~ x 表格是好的。对于lat / long而言,这可能不是你想要的。

edit — ah, you've added back +x and ~~x. As I wrote in a comment, +x is equivalent to using the Number() constructor, but I think it's a little risky because of the syntactic flexibility of the + operator. That is, it'd be easy for a cut-and-paste to introduce an error. The ~~x form is good if you know you want an integer (a 32-bit integer) anyway. For lat/long that's probably not what you want however.

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

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