very simple question, regarding maths in java

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Ibys
    New Member
    • Nov 2009
    • 8

    very simple question, regarding maths in java

    Hi, i am just starting to learn javascript, so i am probably doing something very simple wrong. i have read a lot of articles on maths in java, but cant find anything simple enough for my problem. I am looking for how to get an IF statement to give me the correct output. I am trying to get it to give me a result for a weeks pay, taking that the code worked before i tried to add the IF statement, to make it that if HoursWorked >= 20, the rate of pay would be an extra $2 p/hr. i had the following code to make this work

    Code:
    if (HoursWorked >= 20)
    {
      WeeksPay = parseFloat(HoursWorked) * parseFloat(RateOfPay + 2);
    }
    else
    {
      WeeksPay = parseFloat(HoursWorked) * parseFloat(RateOfPay);
    but, as simple maths will tell you, the answer is not $3800!! can anyone please tel me what silly mistake i am making here please :) sorry to be asking something so simple, but my teacher is away for the weekend and i have just started this module in my course.
  • r035198x
    MVP
    • Sep 2006
    • 13225

    #2
    Java != Javascript.
    I'll assume you meant what you said when you said javascript so I'll move this to the Javascript forum.

    Comment

    • Dormilich
      Recognized Expert Expert
      • Aug 2008
      • 8694

      #3
      what are the HoursWorked and RateOfPay values, before the calculation?

      Comment

      • Ibys
        New Member
        • Nov 2009
        • 8

        #4
        Code:
        HoursWorked=prompt("How many hours did you work this week?","25");
        RateOfPay=prompt("How much are you paid per Hour?","15")
        i dont even know how it is getting the result it is, 3800... all the other tasks i have been doing have been working fine, even the more complicated ones.

        Comment

        • Dormilich
          Recognized Expert Expert
          • Aug 2008
          • 8694

          #5
          that explains it…
          Code:
          parseFloat(RateOfPay + 2)
          the + operator does not only adds numbers, it also concatenates strings. and that’s what’s happening.

          better use
          Code:
          parseFloat(RateOfPay) + 2

          Comment

          • Ibys
            New Member
            • Nov 2009
            • 8

            #6
            thankyou so much! it works fine now :)

            Comment

            Working...