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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With