switch statement - string vs int - javascript

I have this line of javascript in an event handler:
var value = event.currentTarget.value; //example: 9
which I then use in a switch statement.
switch (value) {
case 9:
return 12;
case 12:
return 9;
}
The problem is that "value" is a string instead of an int.
Should I just cast this to an int?
Or is there a way to get the value as an int, like say with jQuery()?
Or should I just use strings in the switch statement?

Or is there a way to get the value as an int, like say with jQuery()?
Of course, this is almost always a feature provided in a language or environment. In JavaScript, there are four ways:
parseInt will parse the string as a whole number. value = parseInt(value, 10) will parse it as decimal (e.g., base 10, the number system most of us use). Note that parseInt will parse the number it finds at the beginning of the string, ignoring anything after it. So parseInt("1blah", 10) is 1.
parseFloat will parse the string as a potentially-fractional number (like 1.2), if the string contains a decimal point. It always works in base 10.
The Number function: value = Number(value). That expects the entire string to be a number, and figures out what number base it is by looking at the string: The default is decimal, but if it starts with 0x it's parsed as hexadecimal (base 16), and on some engines in loose mode if it starts with 0 it's parsed as octal (base 8). There's no way to force it to use a particular number base.
Force the engine to implicitly convert it by applying a math operator to it; the usual one is +. So: value = +value. That does the same thing value = Number(value) does. Oddly, it tends to be slower than Number on some engines, but not enough to matter.
Examples:
parseInt("15", 10): 15
parseFloat("15"): 15
Number("15"): 15
+"15": 15
parseInt("1.4", 10): 1
parseFloat("1.4"): 1.4
Number("1.4"): 1.4
+"1.4": 1.4
parseInt("10 nifty things", 10): 10
parseFloat("10 nifty things"): 10
Number("10 nifty things"): NaN
+"10 nifty things": NaN
Live Copy:
console.log(parseInt("15", 10)); // 15
console.log(parseFloat("15")); // 15
console.log(Number("15")); // 15
console.log(+"15"); // 15
console.log(parseInt("1.4", 10)); // 1
console.log(parseFloat("1.4")); // 1.4
console.log(Number("1.4")); // 1.4
console.log(+"1.4"); // 1.4
console.log(parseInt("10 nifty things", 10)); // 10
console.log(parseFloat("10 nifty things")); // 10
console.log(Number("10 nifty things")); // NaN
console.log(+"10 nifty things"); // NaN
.as-console-wrapper {
max-height: 100% !important;
}

Simple use +value, Notice + in front of a variable with converts the variable to a number
switch (+value) {
case 9:
return 12;
case 12:
return 9;
}

Try this one. parseInt() function does parse a string and returns an integer.
var value = parseInt(event.currentTarget.value, 10);

Related

I am puzzled when i use parseInt from javascript [duplicate]

I'm reading this but I'm confused by what is written in the parseInt with a radix argument chapter
Why is it that parseInt(8, 3) → NaN and parseInt(16, 3) → 1?
AFAIK 8 and 16 are not base-3 numbers, so parseInt(16, 3) should return NaN too
This is something people trip over all the time, even when they know about it. :-) You're seeing this for the same reason parseInt("1abc") returns 1: parseInt stops at the first invalid character and returns whatever it has at that point. If there are no valid characters to parse, it returns NaN.
parseInt(8, 3) means "parse "8" in base 3" (note that it converts the number 8 to a string; details in the spec). But in base 3, the single-digit numbers are just 0, 1, and 2. It's like asking it to parse "9" in octal. Since there were no valid characters, you got NaN.
parseInt(16, 3) is asking it to parse "16" in base 3. Since it can parse the 1, it does, and then it stops at the 6 because it can't parse it. So it returns 1.
Since this question is getting a lot of attention and might rank highly in search results, here's a rundown of options for converting strings to numbers in JavaScript, with their various idiosyncracies and applications (lifted from another answer of mine here on SO):
parseInt(str[, radix]) - Converts as much of the beginning of the string as it can into a whole (integer) number, ignoring extra characters at the end. So parseInt("10x") is 10; the x is ignored. Supports an optional radix (number base) argument, so parseInt("15", 16) is 21 (15 in hex). If there's no radix, assumes decimal unless the string starts with 0x (or 0X), in which case it skips those and assumes hex. (Some browsers used to treat strings starting with 0 as octal; that behavior was never specified, and was specifically disallowed in the ES5 specification.) Returns NaN if no parseable digits are found.
parseFloat(str) - Like parseInt, but does floating-point numbers and only supports decimal. Again extra characters on the string are ignored, so parseFloat("10.5x") is 10.5 (the x is ignored). As only decimal is supported, parseFloat("0x15") is 0 (because parsing ends at the x). Returns NaN if no parseable digits are found.
Unary +, e.g. +str - (E.g., implicit conversion) Converts the entire string to a number using floating point and JavaScript's standard number notation (just digits and a decimal point = decimal; 0x prefix = hex; 0o prefix = octal [ES2015+]; some implementations extend it to treat a leading 0 as octal, but not in strict mode). +"10x" is NaN because the x is not ignored. +"10" is 10, +"10.5" is 10.5, +"0x15" is 21, +"0o10" is 8 [ES2015+]. Has a gotcha: +"" is 0, not NaN as you might expect.
Number(str) - Exactly like implicit conversion (e.g., like the unary + above), but slower on some implementations. (Not that it's likely to matter.)
For the same reason that
>> parseInt('1foobar',3)
<- 1
In the doc, parseInt takes a string. And
If string is not a string, then it is converted to a string
So 16, 8, or '1foobar' is first converted to string.
Then
If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters
Meaning it converts up to where it can. The 6, 8, and foobar are ignored, and only what is before is converted. If there is nothing, NaN is returned.
/***** Radix 3: Allowed numbers are [0,1,2] ********/
parseInt(4, 3); // NaN - We can't represent 4 using radix 3 [allowed - 0,1,2]
parseInt(3, 3); // NaN - We can't represent 3 using radix 3 [allowed - 0,1,2]
parseInt(2, 3); // 2 - yes we can !
parseInt(8, 3); // NaN - We can't represent 8 using radix 3 [allowed - 0,1,2]
parseInt(16, 3); // 1
//'16' => '1' (6 ignored because it not in [0,1,2])
/***** Radix 16: Allowed numbers/characters are [0-9,A-F] *****/
parseInt('FOX9', 16); // 15
//'FOX9' => 'F' => 15 (decimal value of 'F')
// all characters from 'O' to end will be ignored once it encounters the out of range'O'
// 'O' it is NOT in [0-9,A-F]
Some more examples:
parseInt('45', 13); // 57
// both 4 and 5 are allowed in Radix is 13 [0-9,A-C]
parseInt('1011', 2); // 11 (decimal NOT binary)
parseInt(7,8); // 7
// '7' => 7 in radix 8 [0 - 7]
parseInt(786,8); // 7
// '78' => '7' => 7 (8 & next any numbers are ignored bcos 8 is NOT in [0-7])
parseInt(76,8); // 62
// Both 7 & 6 are allowed '76' base 8 decimal conversion is 62 base 10

Numeric conversion in JavaScript [duplicate]

How do parseInt() and Number() behave differently when converting strings to numbers?
Well, they are semantically different, the Number constructor called as a function performs type conversion and parseInt performs parsing, e.g.:
// parsing:
parseInt("20px"); // 20
parseInt("10100", 2); // 20
parseInt("2e1"); // 2
// type conversion
Number("20px"); // NaN
Number("2e1"); // 20, exponential notation
Also parseInt will ignore trailing characters that don't correspond with any digit of the currently used base.
The Number constructor doesn't detect implicit octals, but can detect the explicit octal notation:
Number("010"); // 10
Number("0o10") // 8, explicit octal
parseInt("010"); // 8, implicit octal
parseInt("010", 10); // 10, decimal radix used
And it can handle numbers in hexadecimal notation, just like parseInt:
Number("0xF"); // 15
parseInt("0xF"); //15
In addition, a widely used construct to perform Numeric type conversion, is the Unary + Operator (p. 72), it is equivalent to using the Number constructor as a function:
+"2e1"; // 20
+"0xF"; // 15
+"010"; // 10
typeof parseInt("123") => number
typeof Number("123") => number
typeof new Number("123") => object (Number primitive wrapper object)
first two will give you better performance as it returns a primitive instead of an object.
One minor difference is what they convert of undefined or null,
Number() Or Number(null) Or Number('') // returns 0
while
parseInt() Or parseInt(null) // returns NaN
Summary:
parseInt():
Takes a string as a first argument, the radix (An integer which is the base of a numeral system e.g. decimal 10 or binary 2) as a second argument
The function returns a integer number, if the first character cannot be converted to a number NaN will be returned.
If the parseInt() function encounters a non numerical value, it will cut off the rest of input string and only parse the part until the non numerical value.
If the radix is undefined or 0, JS will assume the following:
If the input string begins with "0x" or "0X", the radix is 16 (hexadecimal), the remainder of the string is parsed into a number.
If the input value begins with a 0 the radix can be either 8 (octal) or 10 (decimal). Which radix is chosen is depending on JS engine implementation. ES5 specifies that 10 should be used then. However, this is not supported by all browsers, therefore always specify radix if your numbers can begin with a 0.
If the input value begins with any number, the radix will be 10
Number():
The Number() constructor can convert any argument input into a number. If the Number() constructor cannot convert the input into a number, NaN will be returned.
The Number() constructor can also handle hexadecimal number, they have to start with 0x.
Example:
console.log(parseInt('0xF', 16)); // 15
// z is no number, it will only evaluate 0xF, therefore 15 is logged
console.log(parseInt('0xFz123', 16));
// because the radix is 10, A is considered a letter not a number (like in Hexadecimal)
// Therefore, A will be cut off the string and 10 is logged
console.log(parseInt('10A', 10)); // 10
// first character isnot a number, therefore parseInt will return NaN
console.log(parseInt('a1213', 10));
console.log('\n');
// start with 0X, therefore Number will interpret it as a hexadecimal value
console.log(Number('0x11'));
// Cannot be converted to a number, NaN will be returned, notice that
// the number constructor will not cut off a non number part like parseInt does
console.log(Number('123A'));
// scientific notation is allowed
console.log(Number('152e-1')); // 15.21
If you are looking for performance then probably best results you'll get with bitwise right shift "10">>0. Also multiply ("10" * 1) or not not (~~"10"). All of them are much faster of Number and parseInt.
They even have "feature" returning 0 for not number argument.
Here are Performance tests.
I found two links of performance compare among several ways of converting string to int.
parseInt(str,10)
parseFloat(str)
str << 0
+str
str*1
str-0
Number(str)
http://jsben.ch/#/zGJHM
http://phrogz.net/js/string_to_number.html
parseInt() -> Parses a number to specified redix.
Number()-> Converts the specified value to its numeric equivalent or NaN if it fails to do so.
Hence for converting some non-numeric value to number we should always use Number() function.
eg.
Number("")//0
parseInt("")//NaN
Number("123")//123
parseInt("123")//123
Number("123ac") //NaN,as it is a non numeric string
parsInt("123ac") //123,it parse decimal number outof string
Number(true)//1
parseInt(true) //NaN
There are various corner case to parseInt() functions as it does redix conversion, hence we should avoid using parseInt() function for coersion purposes.
Now, to check weather the provided value is Numeric or not,we should use nativeisNaN() function
I always use parseInt, but beware of leading zeroes that will force it into octal mode.
It's a good idea to stay away from parseInt and use Number and Math.round unless you need hex or octal. Both can use strings. Why stay away from it?
parseInt(0.001, 10)
0
parseInt(-0.0000000001, 10)
-1
parseInt(0.0000000001, 10)
1
parseInt(4000000000000000000000, 10)
4
It completely butchers really large or really small numbers. Oddly enough it works normally if these inputs are a string.
parseInt("-0.0000000001", 10)
0
parseInt("0.0000000001", 10)
0
parseInt("4000000000000000000000", 10)
4e+21
Instead of risking hard to find bugs with this and the other gotchas people mentioned, I would just avoid parseInt unless you need to parse something other than base 10. Number, Math.round, Math.floor, and .toFixed(0) can all do the same things parseInt can be used for without having these types of bugs.
If you really want or need to use parseInt for some of it's other qualities, never use it to convert floats to ints.
parseInt converts to a integer number, that is, it strips decimals. Number does not convert to integer.
Another way to get the result is to use the ~ operator
For most circumstances
~~someThing === parseInt(something)
but ~~ will return zero for strings that parseInt will accept with trailing other characters or with the number base spec (eg hex) and will also return zero when parseInt returns NaN. Another difference is that ~~ if given a bigint returns a bigint to which you can add another bigint whereas parseInt returns an ordinary floating point number (yes really - it gives exactly the same value as parseFloat) if the bigint is large
However for most circumstances ~~ is 30% faster than parseInt. It is only slower by 10% when something is a floating point represented as a string.
So if the more restricted scope of ~~ fits your need then save the computer time and give yourself less to type

Why is it that parseInt(8,3) == NaN and parseInt(16,3) == 1?

I'm reading this but I'm confused by what is written in the parseInt with a radix argument chapter
Why is it that parseInt(8, 3) → NaN and parseInt(16, 3) → 1?
AFAIK 8 and 16 are not base-3 numbers, so parseInt(16, 3) should return NaN too
This is something people trip over all the time, even when they know about it. :-) You're seeing this for the same reason parseInt("1abc") returns 1: parseInt stops at the first invalid character and returns whatever it has at that point. If there are no valid characters to parse, it returns NaN.
parseInt(8, 3) means "parse "8" in base 3" (note that it converts the number 8 to a string; details in the spec). But in base 3, the single-digit numbers are just 0, 1, and 2. It's like asking it to parse "9" in octal. Since there were no valid characters, you got NaN.
parseInt(16, 3) is asking it to parse "16" in base 3. Since it can parse the 1, it does, and then it stops at the 6 because it can't parse it. So it returns 1.
Since this question is getting a lot of attention and might rank highly in search results, here's a rundown of options for converting strings to numbers in JavaScript, with their various idiosyncracies and applications (lifted from another answer of mine here on SO):
parseInt(str[, radix]) - Converts as much of the beginning of the string as it can into a whole (integer) number, ignoring extra characters at the end. So parseInt("10x") is 10; the x is ignored. Supports an optional radix (number base) argument, so parseInt("15", 16) is 21 (15 in hex). If there's no radix, assumes decimal unless the string starts with 0x (or 0X), in which case it skips those and assumes hex. (Some browsers used to treat strings starting with 0 as octal; that behavior was never specified, and was specifically disallowed in the ES5 specification.) Returns NaN if no parseable digits are found.
parseFloat(str) - Like parseInt, but does floating-point numbers and only supports decimal. Again extra characters on the string are ignored, so parseFloat("10.5x") is 10.5 (the x is ignored). As only decimal is supported, parseFloat("0x15") is 0 (because parsing ends at the x). Returns NaN if no parseable digits are found.
Unary +, e.g. +str - (E.g., implicit conversion) Converts the entire string to a number using floating point and JavaScript's standard number notation (just digits and a decimal point = decimal; 0x prefix = hex; 0o prefix = octal [ES2015+]; some implementations extend it to treat a leading 0 as octal, but not in strict mode). +"10x" is NaN because the x is not ignored. +"10" is 10, +"10.5" is 10.5, +"0x15" is 21, +"0o10" is 8 [ES2015+]. Has a gotcha: +"" is 0, not NaN as you might expect.
Number(str) - Exactly like implicit conversion (e.g., like the unary + above), but slower on some implementations. (Not that it's likely to matter.)
For the same reason that
>> parseInt('1foobar',3)
<- 1
In the doc, parseInt takes a string. And
If string is not a string, then it is converted to a string
So 16, 8, or '1foobar' is first converted to string.
Then
If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters
Meaning it converts up to where it can. The 6, 8, and foobar are ignored, and only what is before is converted. If there is nothing, NaN is returned.
/***** Radix 3: Allowed numbers are [0,1,2] ********/
parseInt(4, 3); // NaN - We can't represent 4 using radix 3 [allowed - 0,1,2]
parseInt(3, 3); // NaN - We can't represent 3 using radix 3 [allowed - 0,1,2]
parseInt(2, 3); // 2 - yes we can !
parseInt(8, 3); // NaN - We can't represent 8 using radix 3 [allowed - 0,1,2]
parseInt(16, 3); // 1
//'16' => '1' (6 ignored because it not in [0,1,2])
/***** Radix 16: Allowed numbers/characters are [0-9,A-F] *****/
parseInt('FOX9', 16); // 15
//'FOX9' => 'F' => 15 (decimal value of 'F')
// all characters from 'O' to end will be ignored once it encounters the out of range'O'
// 'O' it is NOT in [0-9,A-F]
Some more examples:
parseInt('45', 13); // 57
// both 4 and 5 are allowed in Radix is 13 [0-9,A-C]
parseInt('1011', 2); // 11 (decimal NOT binary)
parseInt(7,8); // 7
// '7' => 7 in radix 8 [0 - 7]
parseInt(786,8); // 7
// '78' => '7' => 7 (8 & next any numbers are ignored bcos 8 is NOT in [0-7])
parseInt(76,8); // 62
// Both 7 & 6 are allowed '76' base 8 decimal conversion is 62 base 10

JavaScript - Preventing octal conversion

I'm taking a numerical input as an argument and was just trying to account for leading zeroes. But it seems javascript converts the number into octal before I can do anything to the number. The only way to work around it so far is if I pass the number as a string initially but I was hoping there'd be another way to convert it after it is passed? So far tried (using 017 which alerted me to the octal behaviour):
017.toString(10) // 15
parseInt(017,10) // 15
017 + "" //15
new Number(017) //15
new Number('017') //17
parseInt('017', 10) // 17
So given
function(numb) {
if (typeof numb === number) {
// remove leading zeroes and convert to decimal
}
else {
// use parseInt
}
}
'use strict' also doesn't seem to solve this as some older posts have suggested. Any ideas?
If you take "numerical input", you should always definitely guaranteed have a string. There's no input method in this context that I know that returns a Number. Since you receive a string, parseInt(.., 10) will always be sufficient. 017 is only interpreted as octal if written literally as such in source code (or when missing the radix parameter to parseInt).
If for whatever bizarre reason you do end up with a decimal interpreted as octal and you want to reverse-convert the value back to a decimal, it's pretty simple: express the value in octal and re-interpret that as decimal:
var oct = 017; // 15
parseInt(oct.toString(8), 10) // 17
Though because you probably won't know whether the input was or wasn't interpreted as octal originally, this isn't something you should have to do ever.
JavaScript interprets all numbers beginning with a 0, and containing all octal numerals as octals - eg 017 would be an octal but 019 wouldn't be. If you want your number as a decimal then either
1. Omit the leading 0.
2. Carry on using parseInt().
The reason being is that JavaScript uses a few implicit conversions and it picks the most likely case based on the number. It was decided in JavaScript that a leading 0 was the signal that a number is an octal. If you need that leading 0 then you have to accept that rule and use parseInt().
Source
If you type numbers by hand to script then not use leading zeros (which implicity treat number as octal if it is valid octal - if not then treat it as decimal). If you have number as string then just use + operator to cast to (decimal) number.
console.log(+"017")
if (021 < 019) console.log('Paradox');
The strict mode will not allow to use zero prefix
'use strict'
if (021 < 019) console.log('Paradox');

parseInt method in JavaScript

I am not able to understand what is the use of second parameter of the parseInt method in JavaScript. Below are some of the outputs:
parseInt("9",10) ====> Output: 9
parseInt("9",100) ====> Output: NaN
parseInt("90",10) ====> Output: 9
parseInt("90",100) ====> Output: NaN
Kindly explain what is the use of the second parameter.
The second paramater is known as the Radix -- see here http://en.wikipedia.org/wiki/Radix, which is used to specify the numbering system. See here for a more detailed explanation http://mir.aculo.us/2010/05/12/adventures-in-javascript-number-parsing/
It's the base. So if it's 10, it operates as normally.
parseInt("9",8) ===> NaN
parseInt("7",8) ===> 7
Docs are here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
The radix is used to specify the range of allowed numerals, also known as the number system or base; when omitted, it guesses the value by looking at the prefix of your string, e.g. a "0x" prefix means radix of 16 (hexadecimal). It's a good practice to always set this explicitly to 10 for the decimal system.
When a numeral is outside of the specified radix, parseInt() will return NaN.
As for the NaN result you're seeing with a radix of 100, though not documented per se, the allowed range of the radix is [1, 36], i.e. the largest base comprises digits and alphabets.
Quoting the MDN (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt):
radix
An integer that represents the radix of the above mentioned string. Always specify this parameter to eliminate reader confusion and to guarantee predictable behavior. Different implementations produce different results when a radix is not specified.
Think of it like the base of the number you try to parse, it will return the number in base 10:
parseInt(11,10) // -> 11
parseInt(11,2) //-> 3 (binary)
parseInt(1,6) // 1
parseInt(2,6) // 2
parseInt(3,6) // 3
parseInt(4,6) // 4
parseInt(5,6) // 5
parseInt(6,6) // NaN
parseInt(7,6) // NaN
parseInt(8,6) // NaN
parseInt(9,6) // NaN
parseInt(10,6) // 6, since 5 is the highest digit in base 6 and because of this after 5 comes 10
The 2nd parm is the radix (or base number). The defaut is base 10, so if you omit it, or use 10, then you'll get the same decimal number that you're parsing. If you specify base 16 (hex), then the parsed number is calculated thusly:
Examples:
parseInt("1",16) = 1
parseInt("2",16) = 2
parseInt("3",16) = 3
...
parseInt("9",16) = 9
parseInt("A",16) = 10
parseInt("B",16) = 11
...
parseInt("F",16) = 15
parseInt("10",16) = 16 (1x16 + 0)
parseInt("11",16) = 17 (1x16 + 1)
parseInt("12",16) = 18 (1x16 + 2)
Does that help?
first, some of your example is incorrect. parseInt("90",10) should be output 90.
the second parameter is ary. parseInt("90",10) means parse "90" as decimal.
but why parseInt(xxx, 100) output NaN? You should try parseInt("90", 36) and parseInt("90", 37).
Understand? there are only 36 letter so that no more letter to display the number witch in 37 hex.
finally, sorry about my english.

Categories

Resources