Connecting Tech Pros Worldwide Forums | Help | Site Map

very simple question, regarding maths in java

Newbie
 
Join Date: Nov 2009
Posts: 9
#1: 3 Weeks Ago
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

Expand|Select|Wrap|Line Numbers
  1. if (HoursWorked >= 20)
  2. {
  3.   WeeksPay = parseFloat(HoursWorked) * parseFloat(RateOfPay + 2);
  4. }
  5. else
  6. {
  7.   WeeksPay = parseFloat(HoursWorked) * parseFloat(RateOfPay);
  8.  
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.
best answer - posted by Dormilich
that explains it…
Expand|Select|Wrap|Line Numbers
  1. parseFloat(RateOfPay + 2)
the + operator does not only adds numbers, it also concatenates strings. and that’s what’s happening.

better use
Expand|Select|Wrap|Line Numbers
  1. parseFloat(RateOfPay) + 2

Lives Here
 
Join Date: Sep 2006
Posts: 12,070
#2: 3 Weeks Ago

re: very simple question, regarding maths in java


Java != Javascript.
I'll assume you meant what you said when you said javascript so I'll move this to the Javascript forum.
Dormilich's Avatar
Moderator
 
Join Date: Aug 2008
Location: Leipzig, Germany
Posts: 3,676
#3: 3 Weeks Ago

re: very simple question, regarding maths in java


what are the HoursWorked and RateOfPay values, before the calculation?
Newbie
 
Join Date: Nov 2009
Posts: 9
#4: 3 Weeks Ago

re: very simple question, regarding maths in java


Expand|Select|Wrap|Line Numbers
  1. HoursWorked=prompt("How many hours did you work this week?","25");
  2. 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.
Dormilich's Avatar
Moderator
 
Join Date: Aug 2008
Location: Leipzig, Germany
Posts: 3,676
#5: 3 Weeks Ago

re: very simple question, regarding maths in java


that explains it…
Expand|Select|Wrap|Line Numbers
  1. parseFloat(RateOfPay + 2)
the + operator does not only adds numbers, it also concatenates strings. and that’s what’s happening.

better use
Expand|Select|Wrap|Line Numbers
  1. parseFloat(RateOfPay) + 2
Newbie
 
Join Date: Nov 2009
Posts: 9
#6: 3 Weeks Ago

re: very simple question, regarding maths in java


thankyou so much! it works fine now :)
Reply


Similar JavaScript / Ajax / DHTML bytes