简体   繁体   中英

Decimal value is not showing proper using decimal.Parse

I have this code in vb:

dim d As Object
d = CDec((DateDiff("n", Format(StartTime), "hh:mm tt"), Format(EndTime), "hh:mm tt")) + 1) / 60)

Here, StartTime and EndTime is Date , and value is 09:30 AM and 06:30 PM. This gives me value 9.01666666666667

When i Converted this in C#:

object d;
d = decimal.Parse(((DateAndTime.DateDiff("n", StartTime.ToString("hh:mm tt"), EndTime.ToString("hh:mm tt")) + 1) / 60).ToString());

Here, StartTime and EndTime is DateTime and value is 09:30 and 18:30. This gives me value 9. I do not get a decimal value. Is there anything i am missing? Is it because the EndTime is in 24hrs DateTime format?

The problem you are having is integer division as you have been told in comments. That is an integer divided by an integer will always give an integer as a result. That's how things work in c#. To have a double as your final value one of the operands needs to be a double. In this case you could do that by specifying /60.0 .

However if converting to c# you might as well use some better code than this direct translation. Here's some code that does the same (the first two lines will be omitted in yours since you already have your Date objects).

var startTime = new DateTime(2019,1,11,9,30,0);
var endTime = new DateTime(2019,1,11,18,30,0);

var d = ((endTime-startTime).TotalMinutes+1)/60;
Console.WriteLine(d);

Output:

9.01666666666667

And breaking it down:

endTime-startTime - In c# you can subtract a DateTime object from another and get a TimeSpan object.

.TotalMinutes - Timespan has a TotalMinutes property which is a double representing the total number of minutes of that Timespan - in this case that is returning 540 since our Timespan represents 9 hours or 540 minutes.

The addition and subtraction are pretty straightforward. Of note though is that the division is now a double divided by an integer so the result will be a double and thus not lose the decimal part as your original code did.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM