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?
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With