简体   繁体   English

将字符串转换为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)

second 第二

new Number(x)

third 第三

~~x

fourth 第四

+x

I'd use Number(x) , if I had to choose between those two, because it won't allow trailing garbage. 我使用Number(x) ,如果我必须在这两者之间做出选择,因为它不会允许尾随垃圾。 (Well, it "allows" it, but the result is a NaN .) (嗯,它“允许”它,但结果是NaN 。)

That is, Number("123.45balloon") is NaN , but parseFloat("123.45balloon") is 123.45 (as a number). 即, Number("123.45balloon")NaN ,但是parseFloat("123.45balloon")123.45 (作为数字)。

As Mr. Kling points out, which of those is "better" is up to you. 正如克林先生指出的那样,哪些是“更好”取决于你。

edit — ah, you've added back +x and ~~x . 编辑 - 啊,你已经添加回+x~~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. 正如我在评论中写的那样, +x相当于使用Number()构造函数,但我认为由于+运算符的语法灵活性,它有点风险。 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. 如果你知道你想要一个整数(一个32位整数),那么~~x形式是好的。 For lat/long that's probably not what you want however. 对于纬度/长度,这可能不是你想要的。

The first one is better. 第一个更好。 It is explicit, and it is correct. 它是明确的,而且是正确的。 You said you want to parse floating point numbers. 你说你想要解析浮点数。 ~~x will give you an integer. ~~x会给你一个整数。

To test whether input is number, use this: 要测试input是否为数字,请使用:

function isNumeric(obj){
    return !isNaN( parseFloat(obj) ) && isFinite( obj );
}

To cast String to Number , use + , it's the fastest method : 要将StringNumber ,请使用+这是最快的方法

the unary + operator also type-converts its operand to a number and because it does not do any additional mathematical operations it is the fastest method for type-converting a string into a number 一元+运算符也将其操作数类型转换为数字,因为它不进行任何额外的数学运算,所以它是将字符串转换为数字的最快方法

So overall, probably you need this: 总的来说,可能你需要这个:

if(!isNumeric(inputValue)){
    alert('invalid number');
}else{
    var num = +inputValue;
}

isNumeric borrowed from jQuery isNumericjQuery借来的

This is the code I would write to repeatedly take input until the correct one is obtained. 这是我写的代码,用于重复获取输入,直到获得正确的输入。

var d;

do {
    d = prompt("Enter a number");
    d = new Number(d);
} while( isNaN(d) );

document.write( d );

Note: new Number(d) will always give NaN if any character is non-numeric while parseFloat(d) will ignore trailing invalid characters. 注意:如果任何字符是非数字的,则new Number(d)将始终给出NaN ,而parseFloat(d)将忽略尾随的无效字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM