Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with Math.Truncate(num)

as the question suggests (more of a statement sorry) I'm having problems using math.truncate in C#. What I'm trying to do is say when the decimal of a number divided by 50 is equal to 0.4 do this, as such:

double temp2 = 170;    
temp2 = temp2 / 50;   //this equals 3.4
temp2 -= Math.Truncate(temp2);
if (temp2 == 0.4)
{
    Console.WriteLine("Hello");
}

However when I try to do this it's not working for me and I'm unsure why it's not working, would I be able to get someone to shed some light on this and put me in the right direction please?

like image 206
user2279496 Avatar asked Apr 29 '26 00:04

user2279496


1 Answers

single and double are binary floating-point types. That means they cannot exactly represent many decimal values (like 0.4). This can lead to subtle round-off errors, so comparing two double values that logically should represent the same value can lead to unexpected results.

This can be empirically be verified using the DoubleToInt64Bits method:

BitConverter.DoubleToInt64Bits(temp2); // 4600877379321698712
BitConverter.DoubleToInt64Bits(0.4);   // 4600877379321698714

Change it to decimal and you'll get the result you expect:

decimal temp2 = 170;    
temp2 = temp2 / 50;   //this equals 3.4
temp2 -= Math.Truncate(temp2);
if (temp2 == 0.4m)    // the m creates a decimal constant
{
    Console.WriteLine("Hello");
}
like image 116
p.s.w.g Avatar answered May 01 '26 16:05

p.s.w.g