简体   繁体   中英

Trying to parse a string entry into a double but the point for the decimal is never recognized

There's multiple threads on this where they say to play with CultureInfo but nothing worked for me.

I have a Xamarin.Forms App, the user enters a value that is a string and which can be either written 90, 90.1 or 90,9. Then the value is converted to double to do some calculations.

The xamarin entry component has the attributes "Numeric" so the user can only enter numbers and a point or comma depending on the language of the device.

Since i didn't know in the first place that the language mattered for the point or comma this was my first implementation:

public static double CalculateExposition(TasksGroup group)
{
    return Math.Round(10 * Math.Log10(group.Taches.Sum(x =>
        GetDuration(x.TaskDuration).TotalHours * Math.Pow(10, double.Parse(x.TaskDBA.Replace(",", ".")) / 10.0)) / 8), 1);
}

You can see more details under, thanks a lot for your help.

Problem

This was working all fine with a french emulator on VS 2017 ( somehow i had no keyboard restriction and could do comma and point) until i upgraded my app from vs 2017 to 2019 and tested with an english emulator which uses . for decimal point.

The point is NEVER recognized when i try with an english emulator, so if i put 90.9 it will be recognized like 909.

What i tried (in all threads they say to use CultureInfo but it doesn't do anything for me)

One of the other thing i tried is implementing a custom renderer for the keyboard which was allowing the user to use , or . but apparently i need it to be based on language.

public static double CalculateExposition(TasksGroup group)
{
    return Math.Round(10 * Math.Log10(group.Taches.Sum(x =>
        GetDuration(x.TaskDuration).TotalHours * Math.Pow(10, double.Parse(x.TaskDBA.Replace(",", "."), NumberStyles.Any, CultureInfo.InvariantCulture) / 10.0)) / 8), 1);
}

You can use this extension method:

static class StringExtensions
    {
        private static readonly CultureInfo Fr = new CultureInfo("fr-FR");

        public static decimal ToDecimal(this string value)
        {
            if (value.Contains(','))
                return decimal.Parse(value, Fr);

            return decimal.Parse(value, CultureInfo.InvariantCulture);
        }
    }

If the input string contains a comma then parse it using the French culture. If not, it will be containing a dot or nothing. So parsing it with InvariantCulture (English culture) will do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM