I'm using the following code to mask an entry field for currency. The only issue is I want to limit the input to 2 decimal places. How can I modify the code the accomplish this?
public class CurrencyConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return Decimal.Parse(value.ToString()).ToString("C");
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
string valueFromString = Regex.Replace(value.ToString(), @"\D", "");
if (valueFromString.Length <= 0)
return 0m;
long valueLong;
if (!long.TryParse(valueFromString, out valueLong))
return 0m;
if (valueLong <= 0)
return 0m;
return valueLong / 100m;
}
}
If you want to limit two decimals,you could add the conditions in the entry textchanged event.
like:
<Entry x:Name="entry" Keyboard="Numeric" HorizontalOptions="StartAndExpand" WidthRequest="600" TextChanged="Entry_TextChanged"></Entry>
in the behind code:
private void Entry_TextChanged(object sender, TextChangedEventArgs e)
{
if (e.NewTextValue.Contains("."))
{
if (e.NewTextValue.Length - 1 - e.NewTextValue.IndexOf(".") > 2)
{
var s = e.NewTextValue.Substring(0, e.NewTextValue.IndexOf(".") + 2 + 1);
entry.Text =s;
entry.SelectionLength = s.Length;
}
}
}
the effect: