Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!