Home > Net >  Xamarin Currency Converter Allow Negative
Xamarin Currency Converter Allow Negative

Time:12-28

I have a currency converter class to convert entry input into currency. However, I would like to allow for negative values as well.

<Entry Text="{Binding Price, Converter={StaticResource currencyConverter}}" Keyboard="Numeric" Placeholder="$0.00""/>
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;
        }
    }

CodePudding user response:

You should change the approach with your regular expression then.

Instead of replacing all non-digit characters try to capture digits with possible leading dash.

The regex for this is: ^-?\d $ enter image description here

You can look how this regex works here

And the using of it is a little bit different.

string valueFromString = Regex.Match("", @"^-?\d $").Value;

And the last think: you should remove the last condition, because if the input value would be less than zero, zero would be returned.

if (valueLong <= 0)
    return 0m;

I don't know the rest of the logic into your app, but those would be first steps.

CodePudding user response:

According to the requirements you described, you just want to convert the input number to Decimal type.

  1. You only need to judge whether the input number is negative in the method, if it is negative, you only need to replace the string.

  2. In order to make the code simpler, you can use the Completed method of Entry and judge it internally.

I wrote a small example for your reference:

Here is the background code(Check where notes are added):

 private void Entry_Completed(object sender, EventArgs e)
    {
        int myenry =  int.Parse((sender as Entry).Text.ToString());
        string returnEntry = Decimal.Parse(mytest.Text.ToString()).ToString("C");
        if (myenry < 0) //Judge here and perform string replacement
        {
            returnEntry = returnEntry.Insert(2,"-");
        }
        mytest1.Text = returnEntry;
    }
  • Related