我在驗證錢的輸入時遇到了一些麻煩。我用其他問題中的一些指針來編寫一些更好的代碼。以下是我用來驗證輸入是否是金錢的內容。驗證我的錢
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);
}
結果都不是錢,這對我來說很困惑。
什麼是myIsMaybeMoneyValidator?它在哪裏定義? – Oded 2012-02-07 19:54:53
等待正則表達式的解決方案...另外,爲什麼你不使用正則表達式我敢打賭,有很多很好的例子,他們爲美元。 – 2012-02-07 19:56:21
你需要學習正則表達式 – JoelFan 2012-02-07 19:56:22