3

I am trying to figure out final price based on wage multiplied by hours.

Here is my code Why if the hours are 02:30:00 and the wage: $14 is my total 2?

TimeSpan duration = TimeSpan.Parse("02:30:00"); 
int wage = 14;
var result = (duration.Hours + (duration.Minutes / 60) * wage);
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
N. Sch
  • 667
  • 2
  • 5
  • 15
  • 1
    Please read [MCVE] guidance on posting code. I've edited post's sample to show one option - at the same time it gets clear that totally unrelated [tag:model-view-controller] was not called for on the post at all ([tag:asp.net-mvc] may be a bit better, but not really needed). – Alexei Levenkov Feb 23 '17 at 04:15
  • 1
    Side note: one of standard duplicates for similar question - http://stackoverflow.com/questions/9288904/division-returns-zero answers your question. – Alexei Levenkov Feb 23 '17 at 04:17

1 Answers1

3

First, the expression is actually evaluated as:

duration.Hours + ((duration.Minutes / 60) * cleaner.Price)

Second, you are doing integer division, so 30/60 will result in 0, leaving you with the value 2 i.e. the Hours part.

To fix the issue, you can do something like the below:

(duration.Hours + ((decimal)duration.Minutes / 60)) * 14;

Alternatively, you can skip this component-wise calculation, and just use the TotalHours property instead:

duration.TotalHours * 14
shree.pat18
  • 21,449
  • 3
  • 43
  • 63