Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

decimal to double

Tags:

c#

.net

I have the following test code:

decimal test1 = 0.0500000000000000045656554454M;
double test2 = (double)test1;

This results in test2 showing as 0.05 when debugging. Why is it being rounded to 2 decimal places?

Thanks

like image 487
Jon Archway Avatar asked Dec 05 '22 04:12

Jon Archway


2 Answers

The value from that conversion is actually 0.050000000000000009714451465470119728706777095794677734375, as shown by DoubleConverter. That's the exact value of the nearest double to the decimal you converted.

When you use the debugger or normal string formatting, you aren't usually shown the exact result.

like image 147
Jon Skeet Avatar answered Feb 14 '23 00:02

Jon Skeet


The reason is that double can contain no more than 15-16 significant digits.

see double (C# Reference)

like image 36
Li0liQ Avatar answered Feb 14 '23 01:02

Li0liQ