Rounding a variable to two decimal places C#

Kerry G picture Kerry G · Sep 27, 2012 · Viewed 139.8k times · Source

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);

Answer

Habib picture Habib · Sep 27, 2012

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)

Rounds a decimal value to a specified number of fractional digits.