The Decimal.Round()
method is used to round a decimal value to the nearest integer or number of decimal places.
public static decimal Round (decimal d);
// number of decimal places
public static decimal Round (decimal d, int decimals);
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.
A decimal value that is the decimal number equivalent to d
rounded to decimal places.
// 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));}}
Line 11–13: We create decimal variables d1
, d2
, and d3
.
Line 16–18: We round the values with the Decimal.Round()
method and print them to the console.
// 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);}}
d1
and d2
.d1
to one decimal place.d2
to four decimal places.