0

I am trying to convert a string(format "1.1" or "11.11" and so on..) to a decimal. But the output keeps missing the "." or ","

So I enter "1.1 + 2.2".

first = 1.1 (string)

second = 2.2 (string)

When I try to convert to decimal I get "11" and "22".

Same result if I don't convert "." to ",".

None of the solutions i found on stackoverflow worked.

if (first.Contains("."))
            {
                DecimalMethod(first);
                MessageBox.Show(first);
                first.Replace(".", ",");

            }


            if (second.Contains("."))
            {
                DecimalMethod(second);
                MessageBox.Show(second);
                second.Replace(".", ",");
            }


           decimal.TryParse(first, out firstNumber);
           decimal.TryParse(second, out secondNumber);

1 Answers1

1

I managed to fix it I changed the tryParse part to:

        System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("en-US");
        decimal.TryParse(first, System.Globalization.NumberStyles.Currency,
                             ci, out firstNumber);
       decimal.TryParse(second, System.Globalization.NumberStyles.Currency,
                            ci, out secondNumber);
  • I guess the system you're using is not set as US-English. The number parser follows the PC's Control Panel settings, unless explicitly overridden as you do. Of course, it depends on what you want to do, but consider to avoid to set the culture and rather adjust your Control Panel settings as long you test the application. Also consider that some keyboard layouts use the keypad decimal separator differently. – Mario Vernari Aug 03 '16 at 09:38
  • Have a look at this article of mine: https://highfieldtales.wordpress.com/2014/10/19/numpads-decimal-point-correction-for-wpf/ – Mario Vernari Aug 03 '16 at 09:45