Zack
Zack

Reputation: 13972

How do I parse a string (with commas and the sign at the end, ie. "3,246,928-") in C#?

I've got a string that looks like

3,246,928- 

And I'd like to turn this into a C# double.

Is there a preset format that will parse this as a negative double for me?

I tried

double parsedValue = Double.Parse("3,246,928-");

And get an Exception "Input string was not in a correct format."

Is there a way to do this without manually checking for a negative symbol at the end, stripping it out, stripping the commas, etc..?

Upvotes: 1

Views: 56

Answers (1)

Grant Winney
Grant Winney

Reputation: 66469

You can use the NumberStyles enum to indicate which styles are permitted in the input string:

var input = "3,246,928-";

var res = Double.Parse(input, NumberStyles.AllowThousands | NumberStyles.AllowTrailingSign);

Console.WriteLine(res);  // -3246928

It may also be a good idea to use TryParse instead:

var input = "3,246,928-";

if (Double.TryParse(input, NumberStyles.AllowThousands | NumberStyles.AllowTrailingSign, null, out var result))
    Console.WriteLine(result);  // -3246928

Upvotes: 7

Related Questions