format string modifier for actual number of decimals

  • Thread starter Thread starter Donal McWeeney
  • Start date Start date
D

Donal McWeeney

Hi,

Is there a way to specify on the predefined format strings like P and N that
you want displayed all the decimals in the number...

for example

3 will display 3
2.1 will display 2.1
3.21 will display 3.21

I know I can do it will a custom format like 0.##### but would rather if
these is a handier way...

Thanks

Donal
 
What about using just ToString() without format parameter?

--

Carlos J. Quintero

MZ-Tools 4.0: Productivity add-ins for Visual Studio .NET
You can code, design and document much faster.
http://www.mztools.com
 
Is there a way to specify on the predefined format strings like P and N that
you want displayed all the decimals in the number...

Since you can add an infinite number of zeros to the decimals (2.1,
2.10 or 2.10000000000000...), you need to specify what you mean by
"all the decimals".



Mattias
 
Donal McWeeney said:
Is there a way to specify on the predefined format strings like P and N that you want displayed all the decimals in the number...

If you're using a floating-point number, realize that the number of decimal
places right of the decimal point are going to be difficult to determine due
to rounding or truncation error.
I know I can do it will a custom format like 0.##### but would rather if

I see, you're collecting obfuscated one-liners for a book: "101 Complicated
Ways to Format a Number in .NET."

Here's one approach,

string s = decimalValue.ToString( "N20");
NumberFormatInfo nfi = CultureInfo.CurrentCulture.NumberFormat;
Console.WriteLine(
String.Format( "{{0:N{0}}}",
Math.Max(
0,
s.LastIndexOfAny(
"123456789".ToCharArray( )
) - s.IndexOf( nfi.NumberDecimalSeparator)
)
), decimalValue
);

Hopefully this will convince you to go right ahead with the picture-pattern
format string you're already aware of.

Console.WriteLine( decimalValue.ToString( "0.".PadRight( 20,'#') ) );


Derek Harmon
 
Meant trailing non-zero decimals...

2.1
2.000034

Right, but due to the inexact nature of floating point numbers [1],
the computer may think there are decimals there that you don't expect.
Imagine for example that 3.0 can't be represented exactly, and the
nearest you get is something like 3.00000000000001. Would you still
want to show all those zeros?


[1] See http://www.yoda.arachsys.com/csharp/floatingpoint.html



Mattias
 
Back
Top