locked
Error: Input string was not in correct format RRS feed

  • Question

  • User-73514677 posted

    Hi.

    I have a datarow which contains value as $2,065,890.15

    I am trying to pass the data to SQL table having column type as float. I did the below code:

    if (!string.IsNullOrEmpty(row[1].ToString()))
     {
    row[1] = Decimal.Parse(row[1].ToString(), NumberStyles.Currency, CultureInfo.InvariantCulture);
     }

    I am getting the error as - Input string was not in correct format

    Update1: the issue seems to be with characters , .

    I was able to remove the , ( comma ) character with the replace. How to work with the decimal ?

    How to fix this ?

    Thanks

    Tuesday, March 31, 2020 6:31 AM

Answers

  • User-1330468790 posted

    Hi venkatzeus,

      

    The problem here has nothing to do with the characters ',' and '.'.

    Since you are using the method 'Parse' of the Decimal with the second parameter 'NumberStyles.Currency', the parser can identify ',' and '.'.

      

    Trouble shooting:

    I guess you are not in the region of US so that you should use CultureInfo for 'en-US' instead of "CultureInfo.InvariantCulture".

      

    Solution:

    static void Main(string[] args)
            {
                string s = "$2,065,890.15";
    
                var culture = CultureInfo.GetCultureInfo("en-US");
            
    
                // the parser will automatically remove the $ and ,/. for the string
                string s1 = decimal.Parse(s, NumberStyles.Currency , culture).ToString();
                Console.WriteLine(s1);
                Console.ReadKey();
            }

    Result:

     

    Hope this can help you.

    Best regards,

    Sean

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, March 31, 2020 8:16 AM