Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding a variable to two decimal places C# [duplicate]

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); 
like image 534
Kerry G Avatar asked Sep 27 '12 12:09

Kerry G


People also ask

How do you round something to 2 decimal places?

Rounding a decimal number to two decimal places is the same as rounding it to the hundredths place, which is the second place to the right of the decimal point. For example, 2.83620364 can be round to two decimal places as 2.84, and 0.7035 can be round to two decimal places as 0.70.

How do you round off in C?

The round( ) function in the C programming language provides the integer value that is nearest to the float, the double or long double type argument passed to it. If the decimal number is between “1 and. 5′′, it gives an integer number less than the argument. If the decimal number is between “.

How do you round a double to two decimal places in C#?

double inputValue = 48.00; inputValue = Math. Round(inputValue, 2); will result 48 only.

How do you keep a float up to 2 decimal places?

format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.


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

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

like image 64
Habib Avatar answered Oct 12 '22 12:10

Habib