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
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.You can change this behaviour by using
Math.FloororMath.Ceilon adecimalbefore converting it to along, as seen here.Math.Flooris probably what you need.So: