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 System using System; // create class class Rounder { // main method static void Main() { // create decimal values decimal d1 = 345.453m; decimal d2 = 2.5m; decimal d3 = -4.1115m; // round the values Console.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 System using System; // create class class RoundDecimal { // main method static void Main() { // create decimal values decimal d1 = 23.45m; decimal d2 = 3.4444584854m; // round to some decimal places decimal r1 = Decimal.Round(d1, 1); decimal r2 = Decimal.Round(d2, 4); // print results Console.WriteLine(r1); Console.WriteLine(r2); } }
d1
and d2
.d1
to one decimal place.d2
to four decimal places.RELATED TAGS
CONTRIBUTOR
View all Courses