Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

decimal
round
c#
communitycreator

How to round a decimal value in C#

Theodore Kelechukwu Onyejiaku

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 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));
    }
}
Rounding the decimal numbers into whole number in C#.

Explanation

  • 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.

Example

// 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);
    }
}
Rounding the decimal numbers to specific decimal places in C#.

Explanation

  • Line 10 and 11: We create two decimal variables, d1 and d2.
  • Line 14: We round d1 to one decimal place.
  • Line 15: We round d2 to four decimal places.
  • Line 18 and 19: We print the results.

RELATED TAGS

decimal
round
c#
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring