将字符串转换为javascript中的数字 [英] convert string to a number in 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屋!