Brian
Brian

Reputation: 25834

String.Format Question

MSDN provides a digit placeholder example:
1234.5678 ("#####") -> 1235
I found this confusing (I expected 1234 or something), so I wrote this snippet in C# to test it:

Console.WriteLine(String.Format("{0:#}", 1234.5678));
Console.WriteLine(String.Format("{0:#####}", 1234.5678));
Console.WriteLine(String.Format("{0:#}", "1234.5678"));
Console.WriteLine(String.Format("{0:#####}", "1234.5678"));

It gives this output:

1235
1235
1234.5678
1234.5678

Please explain.

Upvotes: 0

Views: 520

Answers (6)

Scott Dorman
Scott Dorman

Reputation: 42516

The first two String.Format calls are formatting a number (decimal) value. The format string is set to only show the integer portion (before the decimal point) so the value is rounded.

The second two String.Format calls are formatting a string value which happens to contain the string representation of a number. As a result, you are getting back exactly what you provided. The digit placeholder only applies to numeric values which passed to String.Format.

Upvotes: 13

slf
slf

Reputation: 22767

The first two are numbers, so the formatting is applied, they get rounded up and the decimal is thrown away. The second two are strings, so no number formatting is applied to them.

Upvotes: 0

Chris Cudmore
Chris Cudmore

Reputation: 30151

Try:

Console.WriteLine(String.Format("{0:#####.##}", 1234.5678));

Which will give 1234.57

You need to specify the decimal place. Also, the last two are strings, so number formats won't apply.

Upvotes: 2

Dirk Vollmar
Dirk Vollmar

Reputation: 176169

As documented in the MSDN article that you linked, the format specifier ('#') only applies to numeric types.

Custom numeric format specifiers are supported by all of the numeric types in the .NET Framework class library. These include the BigInteger, Byte, Decimal, Double, Int16, Int32, Int64, SByte, Single, UInt16, UInt32, and UInt64 types.

You are passing a string and no numeric type in the third and forth line, hence no formattin is applied.

Upvotes: 0

James Conigliaro
James Conigliaro

Reputation: 3829

The first two formats you are specifying no decimal places so it will round the number accordingly. The last two lines aren't formatting numbers, you are formatting strings, so the numerical formatting doesn't apply.

Upvotes: 0

Instantsoup
Instantsoup

Reputation: 15265

Numbers get rounded as no decimal places are defined in the pattern. Strings don't get rounded, as they're strings.

Upvotes: 0

Related Questions