Home >Backend Development >C++ >How Can I Round Numbers to Two Decimal Places in C# Using Math.Round?
Round numbers to two decimal places using Math.Round in C#
C# provides the Math.Round
function for rounding a number to a specified number of decimal places. To round a number to two decimal places, simply pass in the number and the value 2 as the second argument.
Example:
<code class="language-csharp">decimal a = 1.994444M; Math.Round(a, 2); // 返回 1.99 decimal b = 1.995555M; Math.Round(b, 2); // 返回 2.00</code>
Banker’s Rounding Method
You may also want to consider using Banker's rounding (also known as rounding five to even), which ensures that intermediate values are rounded to the nearest even value. You can achieve this by using the MidpointRounding.ToEven
value as the third parameter of the Math.Round
function.
Example:
<code class="language-csharp">Math.Round(a, 2, MidpointRounding.ToEven);</code>
More resources
For more information about different rounding behaviors in C#, please visit: https://www.php.cn/link/b4e996f75bdf4c28209feba4693ff228
The above is the detailed content of How Can I Round Numbers to Two Decimal Places in C# Using Math.Round?. For more information, please follow other related articles on the PHP Chinese website!