Home > Software design >  Converting string to double returns with the full value, instead of the fraction C#
Converting string to double returns with the full value, instead of the fraction C#

Time:12-02

I am using Visual Studio on MAC (2021) and when I try to convert to double from a string, for example 0,3 it returns with 3. The problem is the Macbook formatting, because it does not recognize ',' as the separator for fractions, instead it uses '.' How do I change it to ',' or make MAC accept both?

string number = "0.3";
double fraction = double.Parse(number);
//this returns 0.3
string number = "0,3";
double fraction = double.Parse(number);
//this returns 3 -> expected to be 0.3 aswell

CodePudding user response:

You can tell double.Parse which decimal separator you want to use:

double fraction = double.Parse(number); // uses the "current culture"    
double fraction = double.Parse(number, CultureInfo.InvariantCulture); // assumes "." as the decimal separator
double fraction = double.Parse(number, CultureInfo.GetCultureInfo("de-DE")); // assumes "," as the decimal separator

However, for your use case, it might be easier to just set the current culture at the start of the program:

CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("hu-HU");

I am teaching in a middle-school, so I have to grade a lot of programming projects, and I don't really want to edit the students code just for running on my laptop

If your students' code assumes that double.Parse(number) always uses a specific decimal separator, your students' code contains a so-called localization bug. If it fits into your syllabus, this could be a great learning opportunity to teach them about localization issues!

  • Related