验证在文化十进制数 [英] validating decimal numbers in culture

查看:189
本文介绍了验证在文化十进制数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以请解释为什么在EN-GB文化的格式,在decimal.Parse()函数将返回15 1,5?

输入1.5,当我看到同样的结果德文化,回报为15。

我知道这是正确的编程,我只是试图理解为什么这是正确的。我GOOGLE了这一点,并拿出什么:(

我试图验证对文化的用户输入,并用0填充输入字段时解析失败,但与15填充字段时,他们已经进入了1,5感觉不对,我觉得像它应该是失败时,1,5是英语格式化输入的,而不是返回15。

 尝试{
        validateSource.Text = decimal.Parse(validateThis,NumberStyles.Number,UserCulture)的ToString();
    } 抓住 {
        validateSource.Text =0;
    }
 

解决方案

是<一个href="http://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.numbergroupseparator(v=vs.110).aspx"><$c$c>NumberGroupSeparator在英国培养。有一个在多少个数字是各组方面没有验证。因此,1,2,3将被解析为123,虽然这不是我们通常会希望它被写入。

虽然这将是有意义的分析检查<一href="http://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.numbergroupsizes(v=vs.110).aspx"><$c$c>NumberGroupSizes物业,根本谈不上。

您可以模拟这种检查在的非常的原始的方式通过格式化解析的结果,看看是否是等于原来的输入:

 十进制值;
如果(decimal.TryParse(文字,NumberStyles.Number,文化,超时值))
{
    如果(文字!= value.ToString(N,文化))
    {
        //好,看起来像回事......报告错误
    }
}
 

当然,这将停止有人进入1234.56,因为它希望1,234.56......你可能要检查的的模式格式,例如: N和G,看它是否与其中之一匹配。

can anyone please explain why, in 'en-GB' culture formatting, the decimal.Parse() function would return 15 for 1,5?

I see the same result for 'de' culture when inputting 1.5, the return is 15.

I know this is programmatically correct, I'm just trying to understand why this is correct. I've Googled this and come up with nothing :(

i'm trying to validate user inputs against culture, and populating the input field with a 0 when the parse fails, but populating the field with 15 when they've entered 1,5 doesn't feel right, i feel like it should be "failing" when a 1,5 is entered for english formating, instead of returning 15.

    try {
        validateSource.Text = decimal.Parse(validateThis, NumberStyles.Number, UserCulture).ToString();
    } catch {
        validateSource.Text = "0";
    }

解决方案

, is the NumberGroupSeparator in the UK culture. There's no validation in terms of how many digits are in each group. So "1,2,3" would be parsed as 123, even though that's not how we'd normally expect it to be written.

While it would make sense for parsing to check the NumberGroupSizes property, it simply doesn't.

You could emulate this check in a very primitive fashion by formatting the result of parsing, and see whether that's equal to the original input:

decimal value;
if (decimal.TryParse(text, NumberStyles.Number, culture, out value))
{
    if (text != value.ToString("N", culture))
    {
        // Okay, looks like something's up... report an error
    }
}

Of course, that would the stop someone from entering "1234.56" as it would expect "1,234.56"... you might want to check multiple pattern formats, e.g. "N" and "G", to see whether it matches any of them.

这篇关于验证在文化十进制数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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