josh
josh

Reputation: 388

parsing a string with a double and getting error input string was not in correct format

I have a string from a csv file that looks like this ""711,200.00"" I am trying to convert that number to a double with this code

collaterel.LoanQty = double.Parse(values[25], CultureInfo.InvariantCulture);

I have taken out the comma and tried to convert to a double and I still get input string was not in correct format

This is what I used to take out the comma

  if (values[25].Contains(","))
  {
     values[25] = values[25].Replace(",", "");
  }

I have tried many culture this still fails.

screen shots double.parse with cultureinfo does not work

enter image description here

enter image description here

enter image description here

Upvotes: 1

Views: 428

Answers (2)

tmaj
tmaj

Reputation: 34947

Use double.Parse.

var s = "711,200.00";

Console.WriteLine(double.Parse(s, System.Globalization.NumberStyles.Number));

prints

711200

NumberStyles.Number is

Number 111

Indicates that the AllowLeadingWhite, AllowTrailingWhite, AllowLeadingSign, AllowTrailingSign, AllowDecimalPoint, and AllowThousands styles are used. This is a composite number style.

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460018

Since double.Parse("711,200.00", CultureInfo.InvariantCulture) works, but your input is ""711,200.00"", you just need to trim the quotes:

collaterel.LoanQty = double.Parse(values[25].Trim('"'), CultureInfo.InvariantCulture);

In general you should use double.TryParse to avoid catching exceptions with invalid formats.

Upvotes: 5

Related Questions