Introducing Radical.sh

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

How to remove trailing zeros in a decimal in C#

The following program explains how to remove the trailing zeros in a decimal type.
Also, it is doing the rounding operation also.

Example:
The following code will remove the trailing zeros as well as rounding the input with four characters after the decimal point.

  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 = { 1.0M, 1.01M, 1.0010M, 0.00M, 1.0050M ,5.001000M,6.12347654333M};
  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 = 1.0, Without Zeros = 1
Original Decimal Number = 1.01, Without Zeros = 1.01
Original Decimal Number = 1.0010, Without Zeros = 1.001
Original Decimal Number = 0.00, Without Zeros = 0
Original Decimal Number = 1.0050, Without Zeros = 1.005
Original Decimal Number = 5.001000, Without Zeros = 5.001
Original Decimal Number = 6.12347654333, Without Zeros = 6.1235


..