Reputation: 5341
I've got a form which allows a user to enter a price, for example, 10.00
.
However as the form is purley text a user could enter $10.00
or 10.00 for book
.
I cannot change the UI, this has to be done under the hood.
So basically what ever the use types I just want a decimal result.
I started to do this
public decimal FilterPrice(dynamic price) {
string convertPrice=price.ToString();
var filterNumber=
from letter in convertPrice
where char.IsDigit(letter)
select letter;
return something;
}
However this will strip out .
. Any ideas how to do this?
Upvotes: 0
Views: 405
Reputation: 1165
You can solve it with a simple Regex.
public bool TryGetPreisAsDecimal(string price, out decimal convertedPrice)
{
Match match = Regex.Match(price,@"\d+(\.\d{1,2})?");
if (match != null)
{
convertedPrice = decimal.Parse(match.Value);
return true;
}
else
{
convertedPrice = 0.0m;
return false;
}
}
Upvotes: 5