I am interested in how to round variables to two decimal places. In the example below, the bonus is usually a number with four decimal places. Is there any way to ensure the pay variable is always rounded to two decimal places?
pay = 200 + bonus; Console.WriteLine(pay); 38 Answers
Use Math.Round and specify the number of decimal places.
Math.Round(pay,2); Math.Round Method (Double, Int32)
Rounds a double-precision floating-point value to a specified number of fractional digits.
Or Math.Round Method (Decimal, Int32)
4Rounds a decimal value to a specified number of fractional digits.
You should use a form of Math.Round. Be aware that Math.Round defaults to banker's rounding (rounding to the nearest even number) unless you specify a MidpointRounding value. If you don't want to use banker's rounding, you should use Math.Round(decimal d, int decimals, MidpointRounding mode), like so:
Math.Round(pay, 2, MidpointRounding.AwayFromZero); // .005 rounds up to 0.01 Math.Round(pay, 2, MidpointRounding.ToEven); // .005 rounds to nearest even (0.00) Math.Round(pay, 2); // Defaults to MidpointRounding.ToEven (Why does .NET use banker's rounding?)
decimal pay = 1.994444M; Math.Round(pay , 2); You can round the result and use string.Format to set the precision like this:
decimal pay = 200.5555m; pay = Math.Round(pay + bonus, 2); string payAsString = string.Format("{0:0.00}", pay); 3Make sure you provide a number, typically a double is used. Math.Round can take 1-3 arguments, the first argument is the variable you wish to round, the second is the number of decimal places and the third is the type of rounding.
double pay = 200 + bonus; double pay = Math.Round(pay); // Rounds to nearest even number, rounding 0.5 will round "down" to zero because zero is even double pay = Math.Round(pay, 2, MidpointRounding.ToEven); // Rounds up to nearest number double pay = Math.Round(pay, 2, MidpointRounding.AwayFromZero); Pay attention on fact that Round rounds.
So (I don't know if it matters in your industry or not), but:
float a = 12.345f; Math.Round(a,2); //result:12,35, and NOT 12.34 ! To make it more precise for your case we can do something like this:
int aInt = (int)(a*100); float aFloat= aInt /100.0f; //result:12,34 1Use System.Math.Round to rounds a decimal value to a specified number of fractional digits.
var pay = 200 + bonus; pay = System.Math.Round(pay, 2); Console.WriteLine(pay); MSDN References:
Console.WriteLine(decimal.Round(pay,2));