How do compiler recognize . as decimal separator?

Asked

Viewed 429 times

2

I made a simple code in C# that receives a real number but only recognizes "," as a decimal separator. When I make you receive numbers that use "." as separator it ignores the point. For example, if sending "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);
        }
     }
}
  • I took the test here and he called me back 2.0. Your code seems to be a little fuzzy too.

1 answer

2


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

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

If you read the console data the conversion may fail by typing something invalid. In something simple you can let it fail, but in a real application it is better to treat this and the best way is with TryParse().

The normal conversion is to be done taking into account 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, 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")));
    }
}

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

Browser other questions tagged

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