How to round a decimal value in C#
Overview
The Decimal.Round() method is used to round a decimal value to the nearest integer or number of decimal places.
Syntax
public static decimal Round (decimal d);
// number of decimal places
public static decimal Round (decimal d, int decimals);
Parameters
-
decimal d: This is the decimal number we want to round. It’s mandatory. -
int decimals: This is the number of decimal places we want to round a decimal number to. It’s optional.
Return value
A decimal value that is the decimal number equivalent to d rounded to decimal places.
Example
// use Systemusing System;// create classclass Rounder{// main methodstatic void Main(){// create decimal valuesdecimal d1 = 345.453m;decimal d2 = 2.5m;decimal d3 = -4.1115m;// round the valuesConsole.WriteLine(Decimal.Round(d1));Console.WriteLine(Decimal.Round(d2));Console.WriteLine(Decimal.Round(d3));}}
Explanation
-
Line 11–13: We create decimal variables
d1,d2, andd3. -
Line 16–18: We round the values with the
Decimal.Round()method and print them to the console.
Example
// use Systemusing System;// create classclass RoundDecimal{// main methodstatic void Main(){// create decimal valuesdecimal d1 = 23.45m;decimal d2 = 3.4444584854m;// round to some decimal placesdecimal r1 = Decimal.Round(d1, 1);decimal r2 = Decimal.Round(d2, 4);// print resultsConsole.WriteLine(r1);Console.WriteLine(r2);}}
Explanation
- Line 10 and 11: We create two decimal variables,
d1andd2. - Line 14: We round
d1to one decimal place. - Line 15: We round
d2to four decimal places. - Line 18 and 19: We print the results.