Skip to content

Instantly share code, notes, and snippets.

@LucioMSP
Created July 22, 2019 14:53
Show Gist options
  • Save LucioMSP/8afa5afdeb3f5c190144e3a229ff5b72 to your computer and use it in GitHub Desktop.
Save LucioMSP/8afa5afdeb3f5c190144e3a229ff5b72 to your computer and use it in GitHub Desktop.
CurrencyConverter.cs
using System;
using Xamarin.Forms;
using System.Globalization;
using System.Text.RegularExpressions;
namespace CurrencyUISample.Converters
{
/// <summary>
/// Converter for using in Entry fields for masked input of currency.
/// <b>The binded property must be of type decimal, and must invoke the
/// PropertyChangedEventArgs event whenever the value is changed, so that the desired mask behavior is kept.</b>
/// </summary>
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;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment