Are there any side effects if i convert a string to a number like below..
var numb=str*1;
If I check with the below code it says this is a number..
var str="123";
str=str*1;
if(!isNaN(str))
{
alert('Hello');
}
Please let me know if there are any concerns in using this method..
When you use
parseFloat, orparseInt, the conversion is less strict.1b5-> 1.Using
1*numberor+numberto convert will result inNaNwhen the input is not valid number. Though unlikeparseInt, floating point numbers will be parsed correctly.Table covering all possible relevant options.
Notes on number conversion methods:
parseIntreturns an integer representation of the first argument. When the radix (second argument) is omitted, the radix depends on the given input.0_= octal (base-8),0x_= hexadecimal (base-16). Default: base-10.parseIntignores any non-digit characters, even if the argument was actually a number: See h, i.To avoid unexpected results, always specify the radix, usually 10:
parseInt(number, 10).parseFloatis the most tolerant converter. It always interpret input as base-10, regardless of the prefix (unlikeparseInt). For the exact parsing rules, see here.The following methods will always fail to return a meaningful value if the string contains any non-number characters. (valid examples:
1.e+0 .1e-1)+n, 1*n, n*1, n/1andNumber(n)are equivalent.~~n, 0|n, n|0, n^1, 1^n, n&n, n<<0andn>>0are equivalent. These are signed bitwise operations, and will always return a numeric value (zero instead ofNaN).n>>>0is also a bitwise operation, but does not reserve a sign bit. Consequently, only positive numbers can be represented, and the upper bound is 232 instead of 231.parseFloatandparseIntwill only look at the.toString()method. The other methods first look for.valueOf(), then.toString(). See q – t.NaN, “Not A Number”:typeof NaN === 'number'NaN !== NaN. Because of this awkwardness, useisNaN()to check whether a value isNaN.When to use which method?
parseFloat( x )when you want to get as much numeric results as possible (for a given string).parseFloat( (x+'').replace(/^[^0-9.-]+/,'') )when you want even more numeric results.parseInt( x, 10 )if you want to get integers.+x, 1*x ..if you’re only concerned about getting true numeric values of a object, rejecting any invalid numbers (asNaN).~~, 0| ..if you want to always get a numeric result (zero for invalid).>>>0if negative numbers do not exists.The last two methods have a limited range. Have a look at the footer of the table.
The shortest way to test whether a given parameter is a real number is explained at this answer: