Home >Backend Development >C++ >How to Round Numbers to Two Decimal Places in C#?
Holding numbers into a specific decimal bit is a common task in programming. C# provides function to simplify this operation.
Math.Round
To use to give up the number into two digits, you can specify the required decimal digits as the second parameter of the function. For example:
In this example, the result value of 1.99 has two decimals. Please note that using the suffix M to indicate the type of variable is decimal.
Math.Round
Self -entry rules and intermediate value treatment
<code class="language-csharp">decimal a = 1.994444M; // 要舍入的示例数字 Math.Round(a, 2); // 返回 1.99</code>
By default,
uses the "far from zero" to give up the rules, of which larger or equal to 0.5 numbers are raised upward, and numbers smaller than 0.5 are settled down. However, you can use the third parameter of the function to specify different entry mode.For example, if you want to use the "banker's entry" or "four houses and five entry", you can specify the value to the third parameter:
Math.Round
The banker enters the middle value between the two values into the closest number. This ensures that the average value of a series of digits is the same as the average value of the original number. Math.Round
MidpointRounding.ToEven
<code class="language-csharp">Math.Round(a, 2, MidpointRounding.ToEven);</code>
The above is the detailed content of How to Round Numbers to Two Decimal Places in C#?. For more information, please follow other related articles on the PHP Chinese website!