var str = '0.5';
var int = 0.1;
I would like the output of str + int
to equal 0.6
Using alert(parseInt(str) + int);
did not yield these results.
var str = '0.5';
var int = 0.1;
I would like the output of str + int
to equal 0.6
Using alert(parseInt(str) + int);
did not yield these results.
alert(parseInt('0.5'))
? Now, how does parseInt differ from parseFloat
? In any case, whenever using parseInt
(where it applies), also specify the radix.
– user166390
Commented
Mar 6, 2013 at 0:54
parseInt
parses your string into an integer:
> parseInt('0.5', 10);
0
Since you want a float, use parseFloat()
:
> parseFloat('0.5');
0.5
There are several ways to convert strings to numbers (integers are whole numbers, which isn't what you want!) in JavaScript (doesn't need jQuery)
By far the easiest is to use the unary + operator:
var myNumber = +myString;
or
alert( (+str) + int );
Also you shouldn't use "int" as a variable name; it's a bad habit (it's often a keyword, and as I said, 0.1 is not an int)
The correct would be using parseFloat
:
var result = parseFloat(str) + int;
alert( result ); // 0.6