How to Round to at Most 2 Decimal Places in C#

Jan 27, 2024

1 min read

Published in

How to round to at most 2 decimal places in C#

Rounding to 2 Decimal Places in C#

Rounding numbers to a specific decimal place is a common task in programming. In C#, you can achieve this easily using the Math.Round function. Let’s create a simple C# program to round a number to at most 2 decimal places.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using System;

class Program
{
    static void Main()
    {
        // Input: A number with more than 2 decimal places
        double originalNumber = 123.456789;

        // Rounding to 2 decimal places
        double roundedNumber = RoundToTwoDecimalPlaces(originalNumber);

        // Output: Display the rounded number
        Console.WriteLine($"Original Number: {originalNumber}");
        Console.WriteLine($"Rounded Number: {roundedNumber}");
    }

    static double RoundToTwoDecimalPlaces(double number)
    {
        // Using Math.Round to round to 2 decimal places
        return Math.Round(number, 2);
    }
}

Explanation

  • We start by defining a sample number with more than 2 decimal places (originalNumber).
  • The RoundToTwoDecimalPlaces function takes a number as input and uses Math.Round to round it to 2 decimal places.
  • In the Main method, we call this function and display both the original and rounded numbers.

Running the Code

Simply copy this code into your C# environment or IDE, and execute the program. You’ll see the original and rounded numbers displayed. This code is straightforward, efficient, and should work flawlessly in various scenarios. Feel free to use and integrate it into your projects where rounding to 2 decimal places is needed.

Sharing is caring!