Jump to content

How to parse the string to an int and add the value in JavaScript?

- - - - -

  • Please log in to reply
3 replies to this topic

#1
Hamed

Hamed

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 276 posts
Hello,
I want to add to number to each other with javascript but it do as string:
function preOrderBook() {
    var num = $('#num').val();
    var cityPrice = $("#city").val();
    var disP = (num * (29000 + cityPrice));
    $("#result").html("هزینه خرید شما:" + disP);
}
disP is int value

#2
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,118 posts
  • Location:Vancouver, Eh! Cleverness: 200
Hello,

Do you mean one of the values is a string and cannot be added, or you wish to display it as a string in the end? I am a little unclear on what you are asking.
Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.

#3
Hamed

Hamed

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 276 posts
look I read cityPrice from select and it is number and should be added to 29000 ex:
29000 + 1000 = 28000
but it show
290001000 and it is wrong!

#4
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,118 posts
  • Location:Vancouver, Eh! Cleverness: 200
It appears .val returns the value of the form, and not the integer value as some languages do. You must use the parseInt function to parse the string in to an integer, before you can add them together. Two strings of numbers will normally concatenate, as you are observing.

... = parseInt($("#city").val())

Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users