Jay Croghan
Jay Croghan

Reputation: 482

Why does C# truncate string precision during Format?

Given a string and a double of equal value, string.Format truncates differently.

double x = 88.2;
string y = "88.2";
string output_1 = String.Format("{0:0.00}", x);
string output_2 = String.Format("{0:0.00}", y);

In this instance, output_1 will be '88.20' and output_2 is '88.2'.

Is there a way to do this without using

Double double_var;
string output;
if (Double.TryParse(input, out double_var))
{
    output = String.Format("{0:0.00}", double_var);
}
else
{
    output = String.Format("{0:0.00}", input);
}

This is for a generic file builder I'm creating for recordsets to files and I would really like to avoid this if possible.

Upvotes: 0

Views: 268

Answers (2)

CodeCaster
CodeCaster

Reputation: 151584

String.Format won't apply a format to a string. You know that the string contains a number, but .NET doesn't.

So yes, you'll have to parse the string to a number and format that number.

From MSDN: String.Format():

A number of types support format strings, including all numeric types (both standard and custom format strings), all dates and times (both standard and custom format strings) and time intervals (both standard and custom format strings), all enumeration types enumeration types, and GUIDs. You can also add support for format strings to your own types.

This does not include strings.

In order for an object to support custom format strings, it needs to implement IFormattable, which the types mentioned above do.

Given these classes:

public class FormattableFoo : IFormattable 
{
    public string ToString(string format, IFormatProvider provider)
    {
        return $"FooFormat: '{format}'";
    }
}

public class Foo
{
    public override string ToString()
    {
        return "Foo";
    }
}

And these calls:

Console.WriteLine("{0:0.00}", new Foo());
Console.WriteLine("{0:0.00}", new FormattableFoo());

The output will be:

Foo
FooFormat: '0.00'

Given System.String doesn't implement IFormattable (and neither does Foo), its ToString() method will be called without a format.

See also MSDN: Customizing Format Strings.

Upvotes: 4

György Kőszeg
György Kőszeg

Reputation: 18013

string does not implement IFormattable so any specified formatting argument will be just ignored. On the other hand, double can interpret the provided 0.00 format specifier.

Side note: C# 6 has a FormattableString but just for supporting different cultures for the format arguments in interpolated strings.

Upvotes: 0

Related Questions