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.
-
2
Well, what happens when you do
alert(parseInt('0.5'))
? Now, how does parseInt differ fromparseFloat
? In any case, whenever usingparseInt
(where it applies), also specify the radix. – user166390 Commented Mar 6, 2013 at 0:54 - 1 Seriously? You're wondering why you don't get the expected fractional result when you're using integer math? – T.J. Crowder Commented Mar 6, 2013 at 0:59
- 1 I don't understand why I get downvoted when I'm trying to learn to program properly and I gain an insightful understanding by getting an answer. I may not be as logical/smart as you, but believe me when I say I aspire to. – O P Commented Mar 6, 2013 at 0:59
3 Answers
Reset to default 8parseInt
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