When I type broken number, it removes the comma and sums as integer

Asked

Viewed 233 times

4

    static void Main(string[] args)
    {
        Console.Write("Digite sua primeira nota: ");
        double n1 = Convert.ToDouble(Console.ReadLine());
        Console.Write("Digite sua segunda nota: ");
        double n2 = Convert.ToDouble(Console.ReadLine());
        double resultado = (n1 + n2) / 2;
        Console.WriteLine("A Média é {0}", resultado);
        Console.ReadKey();
    }

2 answers

8


Probably need to resolve the issue of culture. Anyway various errors can occur in typing. If can’t convert properly can’t let do account.

using static System.Console;

public class Program {
    public static void Main(string[] args) {
        System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("pt-BR");
        Write("Digite sua primeira nota: ");
        double n1;
        if (!double.TryParse(ReadLine(), out n1)) {
            Write("nota digitada errada, estou encerrando, pode tentar novamente");
            return;
        }
        Write("Digite sua segunda nota: ");
        double n2;
        if (!double.TryParse(ReadLine(), out n2)) {
            Write("nota digitada errada, estou encerrando, pode tentar novamente");
            return;
        }
        WriteLine($"A Média é {(n1 + n2) / 2}");
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

8

The source of the problem is your regional Settings (Windows), my computer is regional American, use point in decimals, so your program works using points.

You can solve by forcing your application to use

System.Globalization.CultureInfo

But your application will be fixed to the standard you set, if you distribute it to other regions will have problems.

inserir a descrição da imagem aqui

  • How do I force the application to use System.Globalozation.CultureInfo in C#?

  • 1

    System.Threading.Thread.CurrentThread.Currentculture = new System.Globalization.Cultureinfo("en-BR"); at the beginning of its application

Browser other questions tagged

You are not signed in. Login or sign up in order to post.