如何将NaN从parseInt转换为0 ?

时间:2022-02-21 11:46:40

Is it possible somehow to return 0 instead of NaN when parsing values in JavaScript?

在JavaScript中解析值时,是否可能以某种方式返回0而不是NaN ?

In case of the empty string parseInt returns NaN.

如果是空字符串parseInt返回NaN。

Is it possible to do something like that in JavaScript to check for NaN?

是否可以在JavaScript中执行类似的操作来检查NaN?

var value = parseInt(tbb) == NaN ? 0 : parseInt(tbb)

Or maybe there is another function or jQuery plugin which may do something similar?

或者可能有另一个函数或jQuery插件可以做类似的事情?

13 个解决方案

#1


567  

var s = '';

var num = parseInt(s) || 0;

#2


39  

You can also use the isNaN() function:

还可以使用isNaN()函数:

var s = ''
var num = isNaN(parseInt(s)) ? 0 : parseInt(s)

#3


16  

I was surprised to not see anyone mention using Number(). Granted it will parse decimals if provided, so will act differently than parseInt(), however it already assumes base 10 and will turn "" or even " " in to 0.

我很惊讶没有人提到使用Number()。假设它将解析小数,因此与parseInt()不同,但是它已经假设基数为10,并将“”甚至“”变为0。

#4


5  

For people who are not restricted to parseInt, you can use the bitwise OR operator (which implicitly calls ToInt32 to its operands).

对于不受parseInt限制的人,您可以使用位运算符(它隐式地调用ToInt32作为其操作数)。

var value = s | 0;

// NaN | 0     ==>> 0
// ''  | 0     ==>> 0
// '5' | 0     ==>> 5
// '33Ab' | 0  ==>> 0
// '0x23' | 0  ==>> 35
// 113 | 0     ==>> 113
// -12 | 0     ==>> -12
// 3.9 | 0     ==>> 3

Note: ToInt32 is different from parseInt. (i.e. parseInt('33Ab') === 33)

注:ToInt32不同于parseInt。(即方法(33 ab)= = = 33)

#5


3  

The problem

这个问题

Other answers don't take into account that 0 is falsy, and thus the following will be 20 instead of 0:

其他答案没有考虑到0是假的,因此下面的将是20而不是0:

var myNumber = parseInt('0') || 20; // 20

The solution

解决方案

I propose a helper function, that solves most of the issues:

我提出了一个帮助函数,它可以解决大多数问题:

function getNumber(number, defaultNumber) {
    return isNaN(parseInt(number, 10)) ? defaultNumber : parseInt(number, 10);
}

The helper function will give the following results:

辅助函数将给出以下结果:

getNumber('0', 20); // 0
getNumber('2', 20); // 2
getNumber('2.2', 20); // 2
getNumber('any string', 20); // 20
getNumber(undefined, 20); // 20
getNumber(null, 20); // 20
getNumber(NaN, 20); // 20
getNumber(false, 20); // 20
getNumber(true, 20); // 20

#6


1  

Do a separate check for an empty string ( as it is one specific case ) and set it to zero in this case.

对空字符串进行单独的检查(因为它是一个特定的情况),在这种情况下将其设置为0。

You could appeand "0" to the start, but then you need to add a prefix to indicate that it is a decimal and not an octal number

你可以从“0”开始,但是你需要添加一个前缀来表明它是一个小数而不是八进制数

#7


1  

Why not override the function? In that case you can always be sure it returns 0 in case of NaN:

为什么不重写函数呢?在这种情况下,如果NaN:

(function(original) {
    parseInt = function() {
        return original.apply(window, arguments) || 0;
    };
})(parseInt);

Now, anywhere in your code:

现在,在你代码中的任何地方:

parseInt('') === 0

#8


1  

I had a similar problem (firefox v34) with simple strings like:

我有一个类似的问题(firefox v34),简单的字符串如下:

var myInt = parseInt("b4");

So I came up with a quick hack of:

所以我想到了一个简单的办法:

var intVal = ("" + val).replace(/[^0-9]/gi, "");

And then got all stupid complicated to deal with floats + ints for non-simple stuff:

然后就变得非常复杂去处理浮点数+ ints来处理不简单的东西:

var myval = "12.34";

function slowParseNumber(val, asInt){
    var ret = Number( ("" + val).replace(/[^0-9\.]/gi, "") );
    return asInt ? Math.floor(ret) : ret;
}
var floatVal = slowParseNumber(myval);

var intVal = slowParseNumber(myval, true);
console.log(floatVal, intVal);

It will return 0 for things like:

它会返回0,比如:

var intVal = slowParseNumber("b"); // yeilds 0

#9


1  

var value = isNaN(parseInt(tbb)) ? 0 : parseInt(tbb);

#10


1  

//////////////////////////////////////////////////////
function ToInt(x){x=parseInt(x);return isNaN(x)?0:x;}
//////////////////////////////////////////////////////
var x = ToInt('');   //->  x=0
    x = ToInt('abc') //->  x=0
    x = ToInt('0.1') //->  x=0
    x = ToInt('5.9') //->  x=5
    x = ToInt(5.9)   //->  x=5
    x = ToInt(5)     //->  x=5

#11


0  

Also this way, why not write a function and call it where ever required . I'm assuming it's the entry into the form fields to perform calculations.

同样,为什么不编写一个函数并在需要的地方调用它呢?我假设它是表单字段中执行计算的条目。

var Nanprocessor = function (entry) {
    if(entry=="NaN") {
        return 0;
    } else {
        return entry;
    }
}

 outputfield.value = Nanprocessor(x); 

// where x is a value that is collected from a from field
// i.e say x =parseInt(formfield1.value); 

what's wrong doing this?

这样做有什么问题吗?

#12


0  

Here is a tryParseInt method that I am using, this takes the default value as second parameter so it can be anything you require.

这里是我使用的tryParseInt方法,它将默认值作为第二个参数,所以它可以是任何您需要的东西。

function tryParseInt(str, defaultValue) {
    return parseInt(str) == str ? parseInt(str) : defaultValue;
}

tryParseInt("", 0);//0 
tryParseInt("string", 0);//0 
tryParseInt("558", 0);//558

#13


0  

I created a 2 prototype to handle this for me, one for a number, and one for a String.

我创建了一个2原型来处理这个,一个是一个数字,一个是字符串。

// This is a safety check to make sure the prototype is not already defined.
Function.prototype.method = function (name, func) {
    if (!this.prototype[name]) {
        this.prototype[name] = func;
        return this;
    }
};

// returns the int value or -1 by default if it fails
Number.method('tryParseInt', function (defaultValue) {
    return parseInt(this) == this ? parseInt(this) : (defaultValue === undefined ? -1 : defaultValue);
});

// returns the int value or -1 by default if it fails
String.method('tryParseInt', function (defaultValue) {
    return parseInt(this) == this ? parseInt(this) : (defaultValue === undefined ? -1 : defaultValue);
});

If you dont want to use the safety check, use

如果您不想使用安全检查,请使用

String.prototype.tryParseInt = function(){
    /*Method body here*/
};
Number.prototype.tryParseInt = function(){
     /*Method body here*/
};

Example usage:

使用示例:

var test = 1;
console.log(test.tryParseInt()); // returns 1

var test2 = '1';
console.log(test2.tryParseInt()); // returns 1

var test3 = '1a';
console.log(test3.tryParseInt()); // returns -1 as that is the default

var test4 = '1a';
console.log(test4.tryParseInt(0));// returns 0, the specified default value

#1


567  

var s = '';

var num = parseInt(s) || 0;

#2


39  

You can also use the isNaN() function:

还可以使用isNaN()函数:

var s = ''
var num = isNaN(parseInt(s)) ? 0 : parseInt(s)

#3


16  

I was surprised to not see anyone mention using Number(). Granted it will parse decimals if provided, so will act differently than parseInt(), however it already assumes base 10 and will turn "" or even " " in to 0.

我很惊讶没有人提到使用Number()。假设它将解析小数,因此与parseInt()不同,但是它已经假设基数为10,并将“”甚至“”变为0。

#4


5  

For people who are not restricted to parseInt, you can use the bitwise OR operator (which implicitly calls ToInt32 to its operands).

对于不受parseInt限制的人,您可以使用位运算符(它隐式地调用ToInt32作为其操作数)。

var value = s | 0;

// NaN | 0     ==>> 0
// ''  | 0     ==>> 0
// '5' | 0     ==>> 5
// '33Ab' | 0  ==>> 0
// '0x23' | 0  ==>> 35
// 113 | 0     ==>> 113
// -12 | 0     ==>> -12
// 3.9 | 0     ==>> 3

Note: ToInt32 is different from parseInt. (i.e. parseInt('33Ab') === 33)

注:ToInt32不同于parseInt。(即方法(33 ab)= = = 33)

#5


3  

The problem

这个问题

Other answers don't take into account that 0 is falsy, and thus the following will be 20 instead of 0:

其他答案没有考虑到0是假的,因此下面的将是20而不是0:

var myNumber = parseInt('0') || 20; // 20

The solution

解决方案

I propose a helper function, that solves most of the issues:

我提出了一个帮助函数,它可以解决大多数问题:

function getNumber(number, defaultNumber) {
    return isNaN(parseInt(number, 10)) ? defaultNumber : parseInt(number, 10);
}

The helper function will give the following results:

辅助函数将给出以下结果:

getNumber('0', 20); // 0
getNumber('2', 20); // 2
getNumber('2.2', 20); // 2
getNumber('any string', 20); // 20
getNumber(undefined, 20); // 20
getNumber(null, 20); // 20
getNumber(NaN, 20); // 20
getNumber(false, 20); // 20
getNumber(true, 20); // 20

#6


1  

Do a separate check for an empty string ( as it is one specific case ) and set it to zero in this case.

对空字符串进行单独的检查(因为它是一个特定的情况),在这种情况下将其设置为0。

You could appeand "0" to the start, but then you need to add a prefix to indicate that it is a decimal and not an octal number

你可以从“0”开始,但是你需要添加一个前缀来表明它是一个小数而不是八进制数

#7


1  

Why not override the function? In that case you can always be sure it returns 0 in case of NaN:

为什么不重写函数呢?在这种情况下,如果NaN:

(function(original) {
    parseInt = function() {
        return original.apply(window, arguments) || 0;
    };
})(parseInt);

Now, anywhere in your code:

现在,在你代码中的任何地方:

parseInt('') === 0

#8


1  

I had a similar problem (firefox v34) with simple strings like:

我有一个类似的问题(firefox v34),简单的字符串如下:

var myInt = parseInt("b4");

So I came up with a quick hack of:

所以我想到了一个简单的办法:

var intVal = ("" + val).replace(/[^0-9]/gi, "");

And then got all stupid complicated to deal with floats + ints for non-simple stuff:

然后就变得非常复杂去处理浮点数+ ints来处理不简单的东西:

var myval = "12.34";

function slowParseNumber(val, asInt){
    var ret = Number( ("" + val).replace(/[^0-9\.]/gi, "") );
    return asInt ? Math.floor(ret) : ret;
}
var floatVal = slowParseNumber(myval);

var intVal = slowParseNumber(myval, true);
console.log(floatVal, intVal);

It will return 0 for things like:

它会返回0,比如:

var intVal = slowParseNumber("b"); // yeilds 0

#9


1  

var value = isNaN(parseInt(tbb)) ? 0 : parseInt(tbb);

#10


1  

//////////////////////////////////////////////////////
function ToInt(x){x=parseInt(x);return isNaN(x)?0:x;}
//////////////////////////////////////////////////////
var x = ToInt('');   //->  x=0
    x = ToInt('abc') //->  x=0
    x = ToInt('0.1') //->  x=0
    x = ToInt('5.9') //->  x=5
    x = ToInt(5.9)   //->  x=5
    x = ToInt(5)     //->  x=5

#11


0  

Also this way, why not write a function and call it where ever required . I'm assuming it's the entry into the form fields to perform calculations.

同样,为什么不编写一个函数并在需要的地方调用它呢?我假设它是表单字段中执行计算的条目。

var Nanprocessor = function (entry) {
    if(entry=="NaN") {
        return 0;
    } else {
        return entry;
    }
}

 outputfield.value = Nanprocessor(x); 

// where x is a value that is collected from a from field
// i.e say x =parseInt(formfield1.value); 

what's wrong doing this?

这样做有什么问题吗?

#12


0  

Here is a tryParseInt method that I am using, this takes the default value as second parameter so it can be anything you require.

这里是我使用的tryParseInt方法,它将默认值作为第二个参数,所以它可以是任何您需要的东西。

function tryParseInt(str, defaultValue) {
    return parseInt(str) == str ? parseInt(str) : defaultValue;
}

tryParseInt("", 0);//0 
tryParseInt("string", 0);//0 
tryParseInt("558", 0);//558

#13


0  

I created a 2 prototype to handle this for me, one for a number, and one for a String.

我创建了一个2原型来处理这个,一个是一个数字,一个是字符串。

// This is a safety check to make sure the prototype is not already defined.
Function.prototype.method = function (name, func) {
    if (!this.prototype[name]) {
        this.prototype[name] = func;
        return this;
    }
};

// returns the int value or -1 by default if it fails
Number.method('tryParseInt', function (defaultValue) {
    return parseInt(this) == this ? parseInt(this) : (defaultValue === undefined ? -1 : defaultValue);
});

// returns the int value or -1 by default if it fails
String.method('tryParseInt', function (defaultValue) {
    return parseInt(this) == this ? parseInt(this) : (defaultValue === undefined ? -1 : defaultValue);
});

If you dont want to use the safety check, use

如果您不想使用安全检查,请使用

String.prototype.tryParseInt = function(){
    /*Method body here*/
};
Number.prototype.tryParseInt = function(){
     /*Method body here*/
};

Example usage:

使用示例:

var test = 1;
console.log(test.tryParseInt()); // returns 1

var test2 = '1';
console.log(test2.tryParseInt()); // returns 1

var test3 = '1a';
console.log(test3.tryParseInt()); // returns -1 as that is the default

var test4 = '1a';
console.log(test4.tryParseInt(0));// returns 0, the specified default value