我在验证汇款方面遇到了一些麻烦。我已经使用了其他问题的一些指针来编写更好的代码。以下是我用来验证输入是否是金钱的内容。
static void Main(string[] args)
{
string myTest1 = "$1,234.56";
string myTest2 = "$1.00";
string myTest3 = "$1000.01";
string myTest4 = "$1,234,567.89";
myIsMaybeMoneyValidator Miimv = new myIsMaybeMoneyValidator();
bool myResult1 = Miimv.isMaybeMoney(myTest1);
bool myResult2 = Miimv.isMaybeMoney(myTest2);
bool myResult3 = Miimv.isMaybeMoney(myTest3);
bool myResult4 = Miimv.isMaybeMoney(myTest4);
}
public bool isMaybeMoney(object theirMaybeMoney)
{
string myMaybeMoney = theirMaybeMoney.ToString();
if (myMaybeMoney.StartsWith("-"))
{
myMaybeMoney.Remove(0, 1);
}
if (!myMaybeMoney.StartsWith("$"))
{
return false;
}
myMaybeMoney.Remove(0, 1);
string[] myMaybeMoneyStringArray = myMaybeMoney.Split('.');
string myMaybeMoneyDollars = myMaybeMoneyStringArray[0];
string myMaybeMoneyCents = myMaybeMoneyStringArray[1];
if (!isDollars(myMaybeMoneyDollars))
{
return false;
}
if (!isCents(myMaybeMoneyCents))
{
return false;
}
return true;
}
private bool isDollars(string theirMaybeMoneyDollars)
{
if (!isNumber(theirMaybeMoneyDollars))
return false;
try
{
int myMaybeDollars = Convert.ToInt32(theirMaybeMoneyDollars);
if (myMaybeDollars < 1)
return false;
return true;
}
catch (Exception)
{
return false;
}
return true;
}
private bool isCents(string theirMaybeMoneyCents)
{
if (!isNumber(theirMaybeMoneyCents))
return false;
try
{
int myMaybeCents = Convert.ToInt32(theirMaybeMoneyCents);
if (myMaybeCents > 99)
return false;
if (myMaybeCents < 1)
return false;
return true;
}
catch (Exception)
{
return false;
}
return true;
}
private bool isNumber(object theirMaybeNumber)
{
return Microsoft.VisualBasic.Information.IsNumeric(theirMaybeNumber);
}
结果都不是钱,这让我很困惑。
答案 0 :(得分:11)
看起来在C#中有内置的资金验证。
float num;
bool isValid = float.TryParse(str,
NumberStyles.Currency,
CultureInfo.GetCultureInfo("en-US"), // cached
out num);
答案 1 :(得分:1)
尝试 decimal.TryParse(myTest4,NumberStyles.Currency,new CultureInfo(“en-US”),out myResult4)
答案 2 :(得分:0)
只需使用:
float value;
bool isMoney= float.TryParse(str,
NumberStyles.Currency,
CultureInfo.GetCultureInfo("en-US"),
out value);
如果您想知道代码有什么问题,可能是 Microsoft.VisualBasic.Information.IsNumeric(theirMaybeNumber); 不处理逗号。