How to make the compiler recognize the. as decimal separator?

1

I made a simple C # code that gets a real number but only recognizes the "," as the decimal separator. When I do receive numbers that use the "." as a separator it ignores the point. For example, if you send "2.0", it receives "20". Here is the code:

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

namespace ConsoleApplication4
{
    class Program
    {
       static void Main(string[] args)
       {
           string r;
           double raio;
           r = Console.ReadLine();
           raio = double.Parse(r);
           Console.WriteLine(raio);
        }
     }
}
    
asked by anonymous 12.12.2016 / 04:00

1 answer

1

The compiler already recognizes dotted numbers. What you want to do is have your application do this.

First you need to write a minimally coherent code to at least compile. This one has basic errors.

If the console data is read, the conversion may fail because something invalid is typed. In something simple it can let it fail, but in a real deal it is better to handle this and the best way is to TryParse() .

The normal conversion is done taking into consideration the culture specified in the operating system. If you want a specific culture for your application you need to determine this. There are several ways to do it. It can be for every application, at specific times, you can choose a predefined culture or establish one according to your need. I made a quick example here:

using static System.Console;
using System.Globalization;

namespace ConsoleApplication4 {
    public class Program {
       public static void Main(string[] args) {
           WriteLine(double.Parse("2.0", new CultureInfo("en-US")));
        }
     }
}

See running on dotNetFiddle and on CodingGround .

    
12.12.2016 / 04:30