Home > Backend Development > C++ > How to Round Numbers to Two Decimal Places in C# Using Math.Round?

How to Round Numbers to Two Decimal Places in C# Using Math.Round?

Linda Hamilton
Release: 2025-01-24 10:46:11
Original
898 people have browsed it

How to Round Numbers to Two Decimal Places in C# Using Math.Round?

Rounding Numbers to Two Decimal Places in C# Using Math.Round

Rounding numbers to specified decimal places is a common task in programming. In C#, the Math.Round function provides a convenient way to do this.

The Math.Round function takes two parameters: the number to be rounded and the number of decimal places. To round a number to two decimal places using the Math.Round function, simply specify 2 as the second parameter.

For example:

decimal a = 1.994444M;

Math.Round(a, 2); //returns 1.99
Copy after login

In this example, the number a is rounded to two decimal places, resulting in the value 1.99.

Another example:

decimal b = 1.995555M;

Math.Round(b, 2); //returns 2.00
Copy after login

In this case, the number b is rounded to two decimal places, resulting in the value 2.00.

Bankers Rounding

The Math.Round function also supports bankers rounding, also known as round-to-even. This type of rounding ensures that the result is rounded to the nearest even number if the fractional part is exactly half.

To use bankers rounding, specify the MidpointRounding.ToEven value as the third parameter to the Math.Round function.

For example:

Math.Round(a, 2, MidpointRounding.ToEven);
Copy after login

Additional Resources

For more information on the Math.Round function and bankers rounding, please refer to the following resources:

  • [Math.Round Method (System)](https://docs.microsoft.com/en-us/dotnet/api/system.math.round?view=netcore-3.1)
  • [MidpointRounding Enum (System)](https://docs.microsoft.com/en-us/dotnet/api/system.midpointrounding?view=netcore-3.1)

The above is the detailed content of How to Round Numbers to Two Decimal Places in C# Using Math.Round?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template