11

Is there a display formatter that will output decimals as these string representations in C# without doing any rounding?

The decimal may have 2 decimal places, but if it has more precision it should be included in the resultant string and not rounded off.

Examples:

decimal  -> string
20       -> 20,00
20.00    -> 20,00
20.5     -> 20,50
20.5000  -> 20,50
20.125   -> 20,125
20.12500 -> 20,125

Thanks in advance

Tim Abell
  • 11,186
  • 8
  • 79
  • 110
  • similar but not identical question: http://stackoverflow.com/questions/3104615/best-way-to-display-decimal-without-trailing-zeros-in-c-sharp – Tim Abell Jun 20 '16 at 13:41

1 Answers1

18

When you have a reasonable upper limit for the maximum number of digits:

 ToString("0.00#######")

will handle all your examples but not 1.23456789012345M

H H
  • 263,252
  • 30
  • 330
  • 514
  • If you have no upper limit: `ToString("0.00##########################")`. Decimal type supports at most 28 decimal digits. – l33t Mar 07 '23 at 10:25