简体   繁体   English

c#double.parse()总是使用a。 期间不是逗号

[英]c# double.parse() to always use a . period not comma

How can I specify that my decimal.Parse must always expect to receive a string with a '.' 如何指定我的decimal.Parse必须始终期望接收带有'。'的字符串。 like "4.75" no mater what the system settings of the computer are? 像“4.75”无关电脑的系统设置是什么?

I am reading in a file from excel and it gives me value with a '.' 我正在读取excel的文件,它给了我一个'。'的价值。 and I see that if I run my program on my laptop It throws and error as it expects a ',' 我看到,如果我在我的笔记本电脑上运行我的程序它会抛出错误,因为它期望','

I can use: 我可以用:

string tmp1 = tmp[2].Replace('.', ',');

but then obviously if my computer wants a ''. 但很明显,如果我的电脑想要一个''。 then it will give an error. 那么它会给出一个错误。

What is my best option? 什么是我最好的选择?

See: Double.Parse 请参阅: Double.Parse

Use this overload to specify an IFormatProvider in your case CultureInfo.InvariantCulture . 使用此重载在您的案例CultureInfo.InvariantCulture指定IFormatProvider

var value = double.Parse(tmp[2], CultureInfo.InvariantCulture);

However I would recommend Double.TryParse if you intend to make your process durable. 但是如果你打算让你的过程持久,我会推荐Double.TryParse

double value;

if(!double.TryParse(tmp[2],
   NumberStyles.None,
   CultureInfo.InvariantCulture,
   out value))
{
    // error handling
}

使用Double.Parse Method (String, IFormatProvider)CultureInfo.InvariantCulture进行解析。

double d = double.Parse("2.2", CultureInfo.InvariantCulture);

您可以使用Decimal.Parse的重载,它允许您指定文化:

decimal value = decimal.Parse(tmp[2], CultureInfo.InvariantCulture);

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

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