我在丹麦服务器上维护一个应用程序,我需要检查一个文本框并确保该值大于 1 且小于 26。问题是有些人使用 , 作为小数,有些人使用普通小数。我试过下面的代码,但它在丹麦服务器上不起作用,但它在本地运行良好。任何想法或帮助将不胜感激。谢谢!
if (!String.IsNullOrEmpty(d_m.Text))
{
if (Convert.ToDouble(d_m.Text) < 1 || Convert.ToDouble(d_m.Text) > 25)
{
if (checkfields == false) Response.Write("<tr><td></td><td><font color='red'><b>\"Ship draught\" must be a number greater than 0 and less than 25.</b></font></td></tr>");
requeredFieldsMissing = true;
}
}
最佳答案
尝试如下操作。它依次尝试将文本解析为 double,按偏好降序使用
- 盒子上的当前文化,
- 丹麦文化
- 不变文化
第一个成功解析值的文化获胜。这是代码:
static double? String2Double( string text )
{
CultureInfo[] acceptableCultures =
{
CultureInfo.CurrentCulture , // prefer the current culture on the box
CultureInfo.GetCultureInfo( "da-DK" ) , // then the Danish culture
CultureInfo.InvariantCulture , // and finally, we'll try the invariant culture
} ;
double? value = null ;
for ( int i = 0 ; i < acceptableCultures.Length && !value.HasValue ; ++i )
{
CultureInfo ci = acceptableCultures[i] ;
double v ;
bool parsedSuccessfully = double.TryParse( text , NumberStyles.AllowDecimalPoint , ci , out v ) ;
value = parsedSuccessfully ? v : (double?)null ;
}
return value ;
}
然后你可以这样说:
double? userValue = String2Double( GetUserTextFromTextBox() ) ;
if ( !userValue.HasValue ) throw new ArgumentException( "that's not a number!" );
if ( userValue < 1.0 || userValue > 26.0 ) throw new ArgumentOutOfRangeException( "value must be between 1.0 and 26.0 inclusive" ) ;
关于c# - 如何检查丹麦服务器上的小数边界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30514710/