C# Rounding (Up or Down) or Truncate methods
The methods for rounding numbers to two decimal places in C#, distinguish between those that perform mathematical rounding (up or down) and those that truncate (cut off) without rounding.
Methods that Perform Rounding
These methods round the number according to mathematical rounding rules. For example, they would round 4.456 to 4.46.
1. Math.Round : This method rounds a number to a specified number of fractional digits. If the next digit is 5, it rounds up.
double rounded = Math.Round(number, 2);
2. ToString : This method rounds the number and returns the result as a string.
string formatted = number.ToString(“0.00”);
3. String.Format: This method rounds the number and returns the result in string format.
string formatted = String.Format(“{0:0.00}”, number);
4. String Interpolation: This method rounds the number and returns the result as a string.
string formatted = $”{number:0.00}”;
5. Decimal.Round: For the `decimal` type, this method performs rounding.
decimal rounded = Decimal.Round(number, 2);
Methods that Truncate (Cut Off) Without Rounding
These methods do not round; they simply cut off digits beyond a certain decimal place.
1. Math.Truncate: This removes the fractional part of a number. To truncate to a specific number of decimal places, you multiply the number to elevate the desired digits to the left of the decimal, use this to cut off the excess, and then divide back down to the original scale.
double truncated = Math.Truncate(number * 100) / 100;
Truncating methods are preferred in certain financial calculations or when storing precise values without rounding is required. Rounding methods are more suitable for general use, but as you mentioned, the result of the rounding process can be significant in some scenarios, so it’s important to choose the method type carefully.