Can double lose its precision when converting from decimal in C#?

Viewed 120

For example, I have something like this code:

double a = 68.24;
double b = 0.01;
double c = a - b;

c is equal to 68.22999999999999. And let's say that I cannot change types of a, b and c (it should be double). But I can do this:

double a = 68.24;
double b = 0.01;
decimal _c = (decimal) a - (decimal) b; 
double c = (double)_c;

Now c is 68.23, which is what I need.

But could I lose precision of c converting from decimal _c if I have different values of a and b?

More broadly, when double lose its precision? Because, a and b in debugger are precise (or at least it is what it shows), if I convert them to decimal they are precise too. But operation on them somehow creates imprecise value.

1 Answers

You know how if you try to write out 1/3 using a decimal point, it's impossible do precisely? The same is true of many binary values. When working with floating point values in code, you almost always only have an approximation of the exact value you think you have.

The decimal type helps because is uses the twice the bits to represent a significantly smaller possible range of values (±1028 vs ±10300+). This gives us enough precision the rounding error seems to disappear for most things (it's still there, just too small to notice).

For the sample code in the question, the compiler is detecting we only have constants, and is optimizing away some of the conversions to and from double, so it seems we only work with decimal values until finally outputting the result.

And let's say that I cannot change types of a, b and c (it should be double).

Regardless of that statement, if you care about the accuracy of the result, you probably need decimal.

So why would we ever use double? Speed. The double type is able to take advantage of mathematical instructions implemented and optimized directly in the CPU, making things sometimes 1000s of times faster vs implementing the math operations in software.

Related