Reputation: 187
I have a Windows forms application written in C#.
I am looking for a way to validate my price textBox so that it only accepts prices in a double format e.g. allowing 0.01 & 1200.00 but provides an error when the user enters characters.
I would except the code to looks similar to
String price = tbx_price.Text.Trim();
if price is not a number
{
error message
}
else{
...
What method could I use to check if the price string contains only numbers? Please note that I require the user to be able to use decimal places so the '.' character should be allowed.
Upvotes: 1
Views: 3664
Reputation: 738
Besides using the answer marked as accepted in order to avoid the problem with culture about prices, you can always use this
Convert.ToDouble(txtPrice.Text.Replace(".", ","));
Convert.ToDouble(txtPrice.Text.Replace(",", "."));
this will depend how you manage your convertion in your app.
PS: I could not comment the answer because i do not have the neccesary reputation yet.
Upvotes: 0
Reputation: 9002
You can test this using decimal.TryParse()
.
For example:
decimal priceDecimal;
bool validPrice = decimal.TryParse(price, out priceDecimal);
If you can't be sure that the thread culture is the same as the user's culture, instead use the TryParse()
overload which accepts the culture format (also the number format which you can set to currency):
public bool ValidateCurrency(string price, string cultureCode)
{
decimal test;
return decimal.TryParse
(price, NumberStyles.Currency, new CultureInfo(cultureCode), out test);
}
if (!ValidateCurrency(price, "en-GB"))
{
//error
}
Upvotes: 4
Reputation: 10427
Use decimal.TryParse
:
decimal d;
if (!decimal.TryParse(price, out d)){
//Error
}
And if you also want to validate the price (145.255
is invalid):
if (!(decimal.TryParse(price, out d)
&& d >= 0
&& d * 100 == Math.Floor(d*100)){
//Error
}
Upvotes: 8