Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

204
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda