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

元气小坏坏 提交于 2019-11-29 02:11:50

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.

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();
      }                     
   }
}

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.

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

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

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);
    }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!