Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

207
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda