Home > OS >  I want to change CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator in c#
I want to change CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator in c#

Time:10-08

I am using visual studio 2019. When I use doubles, it uses "," instead ".". I get error if I use ".". I searched around and I can change it but I want to change it inside setting so that it automatically uses "." and not ",".

this is code i use.

double d = double.Parse(Console.ReadLine());
Console.WriteLine(d);

and if i type 4.6 (decimal with .) it gets this error.

Unhandled exception. System.FormatException: Input string was not in a correct format.
   at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type)
   at System.Double.Parse(String s)
   at project3.Program.Main(String[] args) in C:\Users\a2bme\source\repos\project3\Program.cs:line 9

but 4,6 works fine. I have worked with some other languages and am used to ".".

edit:

I know about CultureInfo.InvariantCulture and want a way without using it every time.

CodePudding user response:

If "," is valid and "." is not valid A simple solution can be this. Now you can enter 4.5 or 4,5 and both will work.

using System;
                    
public class Program
{
    public static void Main()
    {
        var input = Console.ReadLine().Replace(".", ",");
        double d = double.Parse(input);
        Console.WriteLine(d);
    }
}

CodePudding user response:

If you only need to format the decimal number use

String.Format("{0:n}", numb)

  • Related