Reputation: 79
I'm having a hard time understand the process of rounding when I convert a decimal to a long.
For example
decimal pi = Convert.ToDecimal(Math.PI);
long d = 2534254324524352;
long dpi = Convert.ToInt64(pi * Convert.ToDecimal(d));
//I'd like to do the reverse to get the value of d as dd
long dd = Convert.ToInt64(Convert.ToDecimal(dpi) /pi);
In this particular example it works but sometimes when I try to get to number back it doesn't work. When you convert a decimal to a long is there an exact way it's rounded? Is there a way to control that behavior?
Thanks
Upvotes: 0
Views: 1030
Reputation: 224974
Convert.ToInt64
, like most default conversion methods, uses banker's rounding, i.e. rounding to the nearest multiple of two. Here's a demo - both 6.5 and 5.5 are rounded to 6.
Console.WriteLine("Rounding 5.5 to {0}", Convert.ToInt64(5.5D)); // 6
Console.WriteLine("Rounding 6.5 to {0}", Convert.ToInt64(6.5D)); // 6
You can change this behaviour by using Math.Floor
or Math.Ceil
on a decimal
before converting it to a long
, as seen here. Math.Floor
is probably what you need.
Console.WriteLine("Rounding 5.5 to {0}", Convert.ToInt64(Math.Floor(5.5D))); // 5
Console.WriteLine("Rounding 6.5 to {0}", Convert.ToInt64(Math.Floor(6.5D))); // 6
So:
decimal pi = Convert.ToDecimal(Math.PI);
long d = 2534254324524352;
long dpi = Convert.ToInt64(Math.Floor(pi * Convert.ToDecimal(d)));
long dd = Convert.ToInt64(Math.Floor(Convert.ToDecimal(dpi) / pi));
Upvotes: 3