Skip to content

Instantly share code, notes, and snippets.

@alfeugds
Last active July 13, 2023 06:01
Show Gist options
  • Star 23 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save alfeugds/786260ab70a49565070338052ceaee3e to your computer and use it in GitHub Desktop.
Save alfeugds/786260ab70a49565070338052ceaee3e to your computer and use it in GitHub Desktop.
Xamarin Forms Currency Mask for Entry fields
using System;
using System.Globalization;
using System.Text.RegularExpressions;
using Xamarin.Forms;
namespace MyProject.Util
{
/// <summary>
/// Converter for using in Entry fields for masked input of currency.
/// <para>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.</para>
/// </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;
}
}
}
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:util="clr-namespace:MyProject.Util;assembly=MyProject"
x:Class="MyProject.View.SomeView"
Title="Some View">
<ContentPage.Resources>
<ResourceDictionary>
<util:CurrencyConverter x:Key="currencyConverter" />
</ResourceDictionary>
</ContentPage.Resources>
<ContentPage.Content>
<StackLayout Padding="20">
<Entry x:Name="ValueConvert" Placeholder="Value" Text="{Binding SomeProperty, Converter={StaticResource currencyConverter}}" Keyboard="Numeric" />
<!-- your fields go here -->
</StackLayout>
</ContentPage.Content>
</ContentPage>
//Create a property in the ViewModel that wraps the decimal property/model you want to receive the currency value
public decimal SomeProperty
{
get {
return YourDecimalProperty;
}
set
{
YourDecimalProperty = value;
//invoke PropertyChangedEventArgs here
//...
}
}
@cammysweet
Copy link

Good work!!!

@peterman304
Copy link

very nicely done!

@programadorthi
Copy link

Works great!

@MDemetrio
Copy link

Work like a charm!
I've also managed to specify a culture in case anyone needs:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            NumberFormatInfo nfi = new CultureInfo("pt-BR").NumberFormat;
            return Decimal.Parse(value.ToString()).ToString("C", nfi);
        }

@jrlsantana
Copy link

Personally, does it work on xamarin.forms 2.3.4.270?
Mine is not returning the mask

@pfarcasanu
Copy link

How do I invoke PropertyChangedEventArgs, can you help me with that?

@ufukhawk
Copy link

ufukhawk commented Aug 8, 2019

Just that..

private decimal _decimalConverter;
    public decimal DecimalConverter
        {
            get => _decimalConverter;
            set
            {
                _decimalConverter = value;
                OnPropertyChanged(nameof(DecimalConverter));
            }
        }

And then
Text="{Binding DeciamConverter, StringFormat='{0:N0}'}"

@Saccomani
Copy link

how allow negative numbers?

@alfeugds
Copy link
Author

You'd probably need to change the ConvertBack() method logic to preserve the negative sign entered from the input.
I'd change the Regex.Replace call to some conditional logic, see if there's a negative sign before any number, and then return the negative number.
It's been a while since I don't play with C# so I can't test it right now =/

@diegosasw
Copy link

I must be doing something wrong..
I always see in the entry text Gs. 0

@tugbaaksoy
Copy link

I have a problem about formatting. I tryed all of sample project . When I want to delete amount , comma is not skipped. For Example , entry amount default : 0,00
I entry 12.345,34 . I pressed backspace key for once. Amount: 1.234,53 , Normally I would expect to set as 12.345,30.

Also When I started to write amount, 0,00 amount isn't deleted. For Example I want to write "3". Amount set as 30,00 .

I can't find where I'm doing wrong. Could you help me with that please ?

@spar
Copy link

spar commented Jul 25, 2020

great work, thank you so much for this.

@devonuto
Copy link

devonuto commented Oct 10, 2021

how allow negative numbers?

public class DecimcalCurrencyConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return decimal.Parse(value.ToString()).ToString("$0.00;-$0.00");
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var isNegative = Regex.IsMatch(value.ToString(), "^-", RegexOptions.CultureInvariant);
        string valueFromString = Regex.Replace(value.ToString(), @"\$|,", "");
        if (valueFromString.Length <= 0)
        {
            return 0m;
        }

        if (!decimal.TryParse(valueFromString, out var decimalVal ))
        {
            return 0m;
        }

        return isNegative ? decimalVal * -1 : decimalVal ;
    }
}

@Geronatsios
Copy link

I have the same problem :
I have a problem about formatting. I tryed all of sample project . When I want to delete amount , comma is not skipped. For Example , entry amount default : 0,00
I entry 12.345,34 . I pressed backspace key for once. Amount: 1.234,53 , Normally I would expect to set as 12.345,30.

Also When I started to write amount, 0,00 amount isn't deleted. For Example I want to write "3". Amount set as 30,00 .

I can't find where I'm doing wrong. Could you help me with that please ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment