使TryParse与逗号或点十进制分隔符兼容 [英] Make TryParse compatible with comma or dot decimal separator

查看:104
本文介绍了使TryParse与逗号或点十进制分隔符兼容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题: 假设您使用的是点."作为您的区域设置中的小数点分隔符,并用逗号编码了字符串.

The problem: Let's assume you are using a dot "." as a decimal separator in your regional setting and have coded a string with a comma.

string str = "2,5";

decimal.TryParse(str, out somevariable);会发生什么?

somevariable将假定为0.

您该怎么解决?

1- 您可以

decimal.TryParse(str, NumberStyles.Any, CultureInfo.InvariantCulture, out somevariable);

它将返回25,而不是2.5,这是错误的.

And it will return 25, and not 2.5 which is wrong.

2- 您可以

decimal.TryParse(str.Replace(",","."), out num);

如果用户使用","作为小数点分隔符,它将返回正确的值,但将不起作用.

And it will return the proper value, BUT, if the user uses "," as a decimal separator it will not work.

可能无法解决的解决方案:

Possible solution that I can't make it work:

在区域设置中获取用户小数点分隔符:

Get the user decimal separator in regional settings:

char sepdec = Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);

并以某种方式从",",sepdec进行替换,这样,如果它是逗号,它将保持逗号,如果用户使用点,则将其替换为实际的点.

And make somehow the replace from ",",sepdec , that way it would stay a comma if its a comma, and replace by an actual dot if the user uses dots.

提示?

最近,许多用户发布了有用的信息,如果将分隔符设置为,",则在tryParse上使用参数NumberStyles.Any, CultureInfo.GetCultureInfo("pt-PT")无效,因此,这几乎不能满足进行tryparse的前提.通用".

Many users posted useful information, lately, using the arguments NumberStyles.Any, CultureInfo.GetCultureInfo("pt-PT") on a tryParse wouldn't work if your separator is set to "," So it pretty much doesnt fullfill the premise of making a tryparse "universal".

如果有人有更多提示欢迎您,我将解决此问题

I'll work around this, if anyone has more hints you'r welcome

推荐答案

我知道该线程较旧,但是我尝试提供一个答案.

I know the thread is a little bit older, but I try to provide an answer.

我使用正则表达式来确定字符串中使用的数字格式. 正则表达式还匹配不带小数点分隔符("12345")的数字.

I use regular expression to determine the used number format in the string. The regex also matches numbers without decimal separators ("12345").

var numberString = "1,234.56"; // en
// var numberString = "1.234,56"; // de
var cultureInfo = CultureInfo.InvariantCulture;
// if the first regex matches, the number string is in us culture
if (Regex.IsMatch(numberString, @"^(:?[\d,]+\.)*\d+$"))
{
    cultureInfo = new CultureInfo("en-US");
}
// if the second regex matches, the number string is in de culture
else if (Regex.IsMatch(numberString, @"^(:?[\d.]+,)*\d+$"))
{
    cultureInfo = new CultureInfo("de-DE");
}
NumberStyles styles = NumberStyles.Number;
bool isDouble = double.TryParse(numberString, styles, cultureInfo, out number);

HTH

托马斯

这篇关于使TryParse与逗号或点十进制分隔符兼容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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