How to convert “12,4” to decimal en-Us culture


流过昼夜 提交于 2019-12-18 03:38:27

问题


I have a decimal value ("133,3") stored in string column in the database, in norway culture.

after that user changed the regional setting to english-Us. when I convert "133,3" to decimal using CultureInfo.InvariantCulture, getting invalid value or error.

is there any best way to handle this scenario in C# application?

regards, Anand


回答1:


Regardless of the system culture, if you specify CultureInfo.InvariantCulture you won't be able to parse "133,3" as a decimal to 133.3. The same is true for US English.

You could just specify a Norwegian culture when parsing the value (using the overload of decimal.TryParse which takes an IFormatProvider), or (preferrably) change the field in the database to reflect the real data type (a decimal number) instead.




回答2:


Do you referred to Convert.ToDecimal(), it says like

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string[] values = { "123456789", "12345.6789", "12 345,6789",
                          "123,456.789", "123 456,789", "123,456,789.0123",
                          "123 456 789,0123" };
      CultureInfo[] cultures = { new CultureInfo("en-US"),
                                 new CultureInfo("fr-FR") }; 

      foreach (CultureInfo culture in cultures)
      {
         Console.WriteLine("String -> Decimal Conversion Using the {0} Culture",
                           culture.Name);
         foreach (string value in values)
         {
            Console.Write("{0,20}  ->  ", value);
            try {
               Console.WriteLine(Convert.ToDecimal(value, culture));
            }
            catch (FormatException) {
               Console.WriteLine("FormatException");
            }
         }
         Console.WriteLine();
      }                     
   }
}



回答3:


If you know the culture that was in use when persisting the value, you can use it when parsing it, i.e.:

Convert.ToDecimal("133,3", System.Globalization.CultureInfo.GetCultureInfo("no"));

Of course, you are probably better off changing how the data is stored in the database, to use a floating point number of some form.




回答4:


Convert.ToDouble(textBox2.Text, new CultureInfo("uk-UA")).ToString(new CultureInfo("en-US"));



回答5:


This solves your problem: .ToString(New CultureInfo("en-US"))




回答6:


used below code to fix my issue. I just hard coded the previous currency decimal part. may not be generic. but solved my problem.

public static decimal? ToDecimal1(this string source)
    {
        CultureInfo usCulture = new CultureInfo("en-US");

        if (string.IsNullOrEmpty(source.Trim1()))
            return null;
        else
            return Convert.ToDecimal(source.Replace(",", ".").Trim(), usCulture);
    }


来源:https://stackoverflow.com/questions/8341810/how-to-convert-12-4-to-decimal-en-us-culture

标签

工具导航Map