Sto riscontrando qualche problema nel convalidare un input di denaro. Ho usato alcuni suggerimenti dalle mie altre domande per scrivere un codice migliore. Quello che segue è ciò che sto usando per convalidare se l'input è o meno denaro.Convalida i miei soldi
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);
}
I risultati non sono tutti soldi, il che è piuttosto confuso per me.
Che cos'è 'myIsMaybeMoneyValidator'? Dove è definito? – Oded
In attesa di una soluzione regex ... Anche perché non stai usando regex Scommetto che ci sono molti esempi molto buoni di loro per USD. –
Hai bisogno di imparare le espressioni regolari – JoelFan