ToDouble格式异常错误

ToDouble格式异常错误

本文介绍了c#Convert.ToDouble格式异常错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将此字符串转换为double

I'm trying to convert this string to double

Convert.ToDouble(1.12);

这是输出

我应该这样做吗?

    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");

还是更容易解决?

推荐答案

double.Parse 将默认使用当前的文化。听起来你想要的是不变的文化:

double.Parse will use the current culture by default. It sounds like you want the invariant culture:

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

编辑:只是为了清楚,显然你不应该使用这个,如果你试图解析用户在不同文化中输入的文字。当您收到不变文化中的数据(如大多数机器到机器数据基于文本的格式),并且要在解析时强制执行此操作,则可以使用此选项。

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.

这篇关于c#Convert.ToDouble格式异常错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 11:52