StoriKnow
StoriKnow

Reputation: 5866

String Format Returns Unexpected Results

I have a simple class that contains a property Format which is set to any given format specifier. I then use the property of this class to, as the name suggest, format the string.

Take the following example:

public class FormatDefinition {
    public string Format { get; set; }
}

class Program {
    static void Main() {

        var formatDefinition = new FormatDefinition {
            Format = "N"
        };

        var number = 20.5;

        var formatOne = string.Format("{0:" + formatDefinition.Format + "}", number);
        var formatTwo = string.Format("{0:formatDefinition.Format}", number);
        var formatThree = $"{number:formatDefinition.Format}";

        Console.WriteLine(formatOne);       //  20.5
        Console.WriteLine(formatTwo);       //  formatDefinition21Format
        Console.WriteLine(formatThree);     //  formatDefinition21Format

        Console.ReadLine();
    }
}

Can someone please explain why formatTwo and formatThree have a result of formatDefinition21Format? It seems the period . is replaced by the formatted number.

Upvotes: 0

Views: 162

Answers (2)

Blorgbeard
Blorgbeard

Reputation: 103467

You are specifying a custom numeric format string consisting of the string "formatDefinition.Format".

This is taken to mean constant string "formatDefinition" followed by the decimal point (and therefore the entire number goes here) followed by constant string "Format".

The number is rounded to zero decimal places because there are no digits specified after the decimal point.

The string formatDefinition.Format is not interpreted as C# code.

Upvotes: 1

Scott Hannen
Scott Hannen

Reputation: 29202

According to the documentation for Custom Number Format Strings:

For fixed-point format strings (that is, format strings that do not contain scientific notation format characters), numbers are rounded to as many decimal places as there are digit placeholders to the right of the decimal point.

It's because you have a decimal point with no digit placeholders to its right. You're telling it to round the number to zero decimal places - in other words, round to the nearest whole number.

These are all functionally the same - all return a22b.

string.Format("{0:a.b}", 21.5);
string.Format("{0:a0b}", 21.5);
string.Format("{0:a0.b}", 21.5);

Here's a DotNetFiddle.

Upvotes: 0

Related Questions