最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - Convert String to Integer with parseInt - Stack Overflow

matteradmin6PV0评论
        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.

Share Improve this question edited Mar 6, 2013 at 0:56 user166390 asked Mar 6, 2013 at 0:53 O PO P 2,36511 gold badges42 silver badges75 bronze badges 3
  • 2 Well, what happens when you do 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
  • 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
Add a ment  | 

3 Answers 3

Reset to default 8

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
Post a comment

comment list (0)

  1. No comments so far