跨区域的十进制/双解析 [英] Cross-regional decimal/double parsing

查看:108
本文介绍了跨区域的十进制/双解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

事实上,我有多个可以生成数字数据的系统,它们存储在某些Web服务器上的文本文件中.有些系统使用小数点作为分数分隔符,有些系统使用小数点逗号相同.

As a matter of fact, I have multiple systems that can generate numeric data and they are stored on some web server in text files. Some of the systems use decimal point as fraction separator, some of the systems use decimal comma as same.

应用程序(胖客户端,.net 2.0)也可以在两种系统上运行.

Applications (fat client, .net 2.0) can also be run on either kind of systems.

因此,在绊脚之后,我这样做了:( http://pastebin.com/vhLXABDD )

So after some stumbling I did this: ( http://pastebin.com/vhLXABDD )

    public static bool HasDecimalComma;
    public static bool HasDecimalPeriod;

    public static double GetNumber(string NumberString)
    {
        if (!HasDecimalComma && !HasDecimalPeriod)
        {
            string s = string.Format("{0:0.0}", 123.123);
            if (s.Contains('.'))
            {
                HasDecimalPeriod = true;
            }
            else if (s.Contains(','))
            {
                HasDecimalComma = true;
            }
            else
            {
                throw new SystemException(string.Format("strange number format '{0}'", s));
            }
        }
        if (HasDecimalComma)
        {
            return double.Parse(NumberString.Replace('.', ','));
        }
        if (HasDecimalPeriod)
        {
            return double.Parse(NumberString.Replace(',', '.'));
        }
        throw new ArgumentException(string.Format("can't parse '{0}'", NumberString));
    }

您会提出更好,更优雅的方法吗?

Would you suggest any better, more elegant way?

很抱歉以前没有提到它,并且由于您的答案都朝那个方向倾斜-我无法用数字存储生成文化,所以我只能尝试检测"它.

I am sorry for not mentioning it before, and since your answers lean in that direction - I can't store generating culture with the numbers, I can only try to 'detect' it.

推荐答案

尝试一下:

    static double GetDouble(string s)
    {
        double d;

        var formatinfo = new NumberFormatInfo();

        formatinfo.NumberDecimalSeparator = ".";

        if (double.TryParse(s, NumberStyles.Float, formatinfo, out d))
        {
            return d;
        }

        formatinfo.NumberDecimalSeparator = ",";

        if (double.TryParse(s, NumberStyles.Float, formatinfo, out d))
        {
            return d;
        }

        throw new SystemException(string.Format("strange number format '{0}'", s));
    }

这篇关于跨区域的十进制/双解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆