c# Convert.ToDouble 格式异常错误
我正在尝试将此字符串转换为双精度
Convert.ToDouble("1.12");
这是输出
System.FormatException 未处理。
我应该做这样的事情吗?
public static double ConvertToDouble(string ParseVersion)
{
double NewestVersion;
try
{
NewestVersion = Convert.ToDouble(ParseVersion);
}
catch
{
ParseVersion = ParseVersion.Replace('.', ',');
NewestVersion = Convert.ToDouble(ParseVersion);
}
return NewestVersion;
}
ConvertToDouble("1.12");
或者有更简单的解决方案吗?
I'm trying to convert this string to double
Convert.ToDouble("1.12");
and this is the output
System.FormatException was unhandled.
Should I do something like this?
public static double ConvertToDouble(string ParseVersion)
{
double NewestVersion;
try
{
NewestVersion = Convert.ToDouble(ParseVersion);
}
catch
{
ParseVersion = ParseVersion.Replace('.', ',');
NewestVersion = Convert.ToDouble(ParseVersion);
}
return NewestVersion;
}
ConvertToDouble("1.12");
Or is there an easier solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
double.Parse
默认情况下将使用当前区域性。听起来您想要不变的文化:编辑:只是为了清楚起见,如果您尝试解析不同文化中的用户输入的文本,显然您不应该使用它。当您以固定区域性接收数据(就像大多数机器对机器数据基于文本的格式一样)并希望在解析时强制执行时,可以使用此方法。
double.Parse
will use the current culture by default. It sounds like you want the invariant culture:EDIT: Just to be clear, obviously you shouldn't use this if you're trying to parse text entered by a user in a different culture. This is for use when you've received data in the invariant culture (as most machine-to-machine data text-based formats are) and want to enforce that when parsing.
您不必将
.
替换为,
.. 但是更好的方法是使用 .netTryParse
方法,例如:编辑: 另请注意,通过用
替换
您会得到错误的结果,例如.
,1.12
:You don't have to replace
.
to,
.. however a better way is to use the .netTryParse
method like:Edit: Also note that by replacing
.
by,
you are getting a wrong results, for instance1.12
:Convert.ToDouble 在内部使用 Double.Parse。如果您不确定文化背景,则应该使用 Double.Parse 的重载来精确确定文化:
Convert.ToDouble uses Double.Parse internally. If you are unsure of the culture context, you should use an overload of Double.Parse precising the culture:
请记住,此问题可能取决于输入字符串的来源。如果它作为对象从数据库中读取,您可以通过将其保留为对象并使用 Convert.ToDouble() 来解决您的问题,如下所示:
Keep in mind, this problem can depend on where the input string comes from. If it is read from a database as an object, you might solve your problem by keeping it as an object and using Convert.ToDouble() as follows: