Sunday 6 October 2019

c# - Convert Double --> Decimal not exactly








Help me.



I am developing a application in C# . I am trying:



DateTime dtm1 = new DateTime(2012, 11, 15, 11, 3, 0);
DateTime dtm2 = new DateTime(2012, 11, 15, 11, 3, 20);
TimeSpan timespan3 = dtm2 - dtm1;
decimal _Hour = Convert.ToDecimal(timespan3.TotalHours);



When do such me with output as follows:



 _Hour = 0.00555555555555556M


and the which is not exactly, when using is a type of double it for output:



 double _Hour = timespan3.TotalHours;


output: 0.0055555555555555549


One for example:



public decimal tinhDienTichHinhThang(decimal D1, decimal D2, decimal H)
{
//tính tổng 2 đáy
decimal tong2Day = D1 + D2;
//cộng vào nhân chiều cao :))

tong2Day = tong2Day * H;

//return diện tích
return tong2Day / 2;
}


DateTime dtm1 = new DateTime(2012, 11, 15, 11, 3, 0);
DateTime dtm2 = new DateTime(2012, 11, 15, 11, 3, 20);
TimeSpan timespan3 = dtm2 - dtm1;


///progress
///cal1: _Hour
///cal2: decimal D1 = 0.25
///cal3: decimal D2 = 5
///cal4: decimal D3 = 0.9

decimal test1 = (decimal test1 = Math.Round((D1 + tinhDienTichHinhThang(D2, 0, Convert.ToDecimal(timespan3.TotalHours))) * D3, 3, MidpointRounding.AwayFromZero);



output: test1 = 0.237



if calculate manual:



test1 =  Math.Round((0.25 + ((5+0)*timespan3.TotalHours/2))*0.9, 3, MidpointRounding.AwayFromZero);


output:test1 = 0.238 (exactly: 0.2375)



Note: Calculate win XP then exactly: 0.2375

But calculate win 7 then not exactly.



Please interpret cho me the problem that why and resolve this problem with the way?

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...