Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Convert.ToDecimal(Double) round to 15 significant figures?

Tags:

c#

double

decimal

I have a double with 17 digits after the decimal point, i.e.:

double myDouble = 0.12345678901234567;

If I convert this to a decimal like this:

decimal myDecimal = Convert.ToDecimal(myDouble);

then the value of myDecimal is rounded, as per the Convert.ToDecimal documentation, to 15 digits (i.e. 0.0123456789012345). My question is, why is this rounding performed?

I understand that if my original number could be accurately represented in base 10 and I was trying to store it as a double, then we could only have confidence in the first 15 digits. The final two digits would be subject to rounding error. But, that's a base 10 biased point of view. My number may be more accurately represented by a double and I wish to convert it to decimal while preserving as much accuracy as possible.

Shouldn't Convert.ToDecimal aim to minimise the difference between myDouble and (double)Convert.ToDecimal(myDouble)?

like image 472
eoinmullan Avatar asked Feb 03 '26 07:02

eoinmullan


1 Answers

From the documentation of Double:

A Double value has up to 15 decimal digits of precision, although a maximum of 17 digits is maintained internally

So, as the double value itself has a maximum of 15 decimal places, converting it to Decimal will result in a Decimal value with 15 significant figures.

like image 198
stuartd Avatar answered Feb 04 '26 21:02

stuartd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!