moik
moik

Reputation: 165

Converting number in string with negative sign at the end

From the MSDN documentation I should use NumberFormatInfo's NumberNegativePattern property to set the expected pattern for negative number values.

So I tried:

var format = new NumberFormatInfo {NumberNegativePattern = 3};
Console.WriteLine(Convert.ToDouble("1.000-", format));

But I always receive a FormatException saying "Input string was not in a correct format.". I also tried formatting with NumberFormatInfo.InvariantInfo - with same results.

Upvotes: 0

Views: 3793

Answers (2)

Soner Gönül
Soner Gönül

Reputation: 98740

Your NumberFormatInfo's NumberNegativePattern assigned to 3 but the other properties of your NumberFormatInfo will be depends on your CurrentCulture. But that's not the point there.

This Convert.ToDouble(String, IFormatProvider) method implemented as;

public static double ToDouble(String value)
{
    if (value == null)
        return 0;
    return Double.Parse(value, CultureInfo.CurrentCulture);
}

and Double.Parse(String, IFormatProvider) implemented as;

public static double Parse(String s, IFormatProvider provider)
{
   return Parse(s, NumberStyles.Float| NumberStyles.AllowThousands, NumberFormatInfo.GetInstance(provider));
}

And NumberStyles.Float doesn't have NumberStyles.AllowTrailingSign, that's why your code throws FormatException.

It is really hard to tell your 1.000 value is 1 with decimal point or 1000 with thousand separator, but you can use AllowDecimalPoint or AllowThousands styles with AllowTrailingSign style as a second parameter of Double.Parse(String, NumberStyles) overload.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1499770

You don't need a format here - it looks like the NumberNegativePattern is only used when formatting, not parsing, and then only for the N format. However, there's a NumberStyles value for this:

Console.WriteLine(double.Parse("1.000-", 
    NumberStyles.AllowTrailingSign | NumberStyles.AllowDecimalPoint));

Upvotes: 6

Related Questions