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);
Make 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.
You can round the result and use
string.Format
to set the precision like this:You should use a form of
Math.Round
. Be aware thatMath.Round
defaults to banker's rounding (rounding to the nearest even number) unless you specify aMidpointRounding
value. If you don't want to use banker's rounding, you should useMath.Round(decimal d, int decimals, MidpointRounding mode)
, like so:(Why does .NET use banker's rounding?)
Use System.Math.Round to rounds a decimal value to a specified number of fractional digits.
MSDN References: