Introducing Radical.sh

Forget Code launches a powerful code generator for building API's

Round the Decimal value in C#

The following codes explain the rounding operation in Decimal types.
The "#" symbol defines the rounding value here.

Example 1:

Rounding for 4

  1. using System;
  2. using System.Text;
  3.  
  4. namespace forgetCode
  5. {
  6.  
  7. class program
  8. {
  9. public static void Main()
  10. {
  11. decimal[] decimalNumbers = {6.12347654333M,4.34446M};
  12.  
  13. foreach (decimal decimalNumber in decimalNumbers)
  14. {
  15. Console.WriteLine("Original Decimal Number = {0}, Without Zeros = {1}",
  16. decimalNumber, decimalNumber.ToString("0.####"));
  17. }
  18. }
  19. }
  20. }


Output:
Original Decimal Number = 6.12347654333, Without Zeros = 6.1235
Original Decimal Number = 4.34446, Without Zeros = 4.3445

Example 2:

Rounding for 2

  1. using System;
  2. using System.Text;
  3.  
  4. namespace forgetCode
  5. {
  6.  
  7. class program
  8. {
  9. public static void Main()
  10. {
  11. decimal[] decimalNumbers = {6.12347654333M,4.34446M};
  12.  
  13. foreach (decimal decimalNumber in decimalNumbers)
  14. {
  15. Console.WriteLine("Original Decimal Number = {0}, Without Zeros = {1}",
  16. decimalNumber, decimalNumber.ToString("0.##"));
  17. }
  18. }
  19. }
  20. }



Output:

Original Decimal Number = 6.12347654333, Without Zeros = 6.12
Original Decimal Number = 4.34446, Without Zeros = 4.34