简体   繁体   English

将字符串转换为 double 返回完整值,而不是分数 C#

[英]Converting string to double returns with the full value, instead of the fraction C#

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 '.'我在 MAC (2021) 上使用 Visual Studio,当我尝试从字符串转换为 double 时,例如 0,3,它返回 3。问题是 Macbook 格式,因为它无法将“,”识别为分隔符对于分数,而是使用“。” How do I change it to ',' or make MAC accept both?我如何将其更改为“,”或让 MAC 接受两者?

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

You can tell double.Parse which decimal separator you want to use:您可以告诉double.Parse您要使用哪个小数点分隔符:

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 .如果您的学生代码假定double.Parse(number)始终使用特定的小数点分隔符,则您学生的代码包含所谓的本地化错误 If it fits into your syllabus, this could be a great learning opportunity to teach them about localization issues!如果它适合您的教学大纲,这可能是一个很好的学习机会,可以教他们本地化问题!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM