¿Por qué System.Convert ( “0”) lanzar una FormatException en algunos sistemas?

StackOverflow https://stackoverflow.com/questions/4461709

  •  10-10-2019
  •  | 
  •  

Pregunta

El código se compila en VS2008 .NET3.5 orientación. Esto no es reproducible en mi sistema. Sospecho algún tipo de ajuste de la localización es en el juego, pero no sé mucho acerca de eso.

El resto de números válidos parece que funcionan bien. El fallo de funcionamiento se ilustra con este código (que causa la misma excepción pero no es el código de producción):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "";
            do
            {
                str = Console.ReadLine();
                Console.WriteLine("\t\"{0}\"", Convert.ToDouble(str));
            }
            while (str != null);
        }
    }
}

En la línea de comandos, introducción de "0" se bloquea la aplicación en al menos un sistema que he encontrado.

Seguimiento de la pila desde el PC del usuario:

System.FormatException: Input string was not in a correct format.
   at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
   at System.Number.ParseDouble(String value, NumberStyles options, NumberFormatInfo numfmt)
   at System.Double.Parse(String s, NumberStyles style, NumberFormatInfo info)
   at System.Convert.ToDouble(String value)
¿Fue útil?

Solución

I remember this problem from a question a while back. The Parse() methods are affected by the user overrides in the Control Panel + Region and Language applet. IIRC, it is especially sensitive to the "Negative sign symbol" setting. Ask your user to correct the settings there.

The reference question is here.

Otros consejos

If your problem is related to current culture, try converting to Double using Invariant Culture:

Convert.ToDouble("0", System.Globalization.CultureInfo.InvariantCulture);

It's quite easy to prove that it's not because of the code(or the CultureInfo), I can prove that for all cultures in .NET, a string "0" can be converted to double correctly.

string inputNumber = "0";
foreach (var culture in CultureInfo.GetCultures(CultureTypes.AllCultures))
{
   try
   {
       double d = Convert.ToDouble(inputNumber, culture);
   }
   catch
   {
      Console.WriteLine(culture.Name);
   }
}
Console.WriteLine("end");
Console.Read();

It outputs nothing but an "end".

It might be related to culture settings. As I know in some culture settings you should type in 0.0 to be able to convert to double

I don't think it does crash when you input 0.

It will, of course, crash when you input anything that is not a number. This means that it will crash if you input an empty string (in other words, just push enter). I imagine this is what you are experiencing.

You code would work (for only numbers) if you change it to this:

string str = "";
do
{
    str = Console.ReadLine();
    if(!string.IsNullOrEmpty(str))
        Console.WriteLine("\t\"{0}\"", Convert.ToDouble(str));
}
while (str != "");

The CurrentCulture CultureInfo instance is probably to blame. Convert.ToDouble call, after all, simply returns the result of Double.Parse. This, as documented, uses the current culture's NumberFormatInfo to figure things out.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top