Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

long.Parse() C#

Tags:

c#

.net-3.5

How would I convert a string, say "-100,100", to long in C#.

I currently have a line of code which is

long xi = long.Parse(x, System.Globalization.NumberStyles.AllowThousands);

but this breaks when x is "a negative number".

My approach:

long xi = long.Parse("-100,253,1", 
System.Globalization.NumberStyles.AllowLeadingSign & System.Globalization.NumberStyles.AllowThousands);

was wrong, as it broke.

like image 951
ViV Avatar asked May 23 '12 07:05

ViV


People also ask

What is long parse?

The parseLong() method of Java Long class is used to parse the CharSequence argument as a signed long with the specified radix , beginning at a specified beginIndex and extending to endIndex-1.

What is TryParse C#?

In C#, Char. TryParse() is Char class method which is used to convert the value from given string to its equivalent Unicode character.

Can we convert long to int in C#?

ToInt32(long) Method is used to convert a specific 64-bit signed integer (long) value to its equivalent 32-bits signed integer (int32). Note: Value to be converted should not exceed the range of a signed 32-bit integer. Syntax: int Convert.


2 Answers

give this a go:

long xi = long.Parse(x, System.Globalization.NumberStyles.AllowThousands | System.Globalization.NumberStyles.AllowLeadingSign);

It may well be because you are declaring flags you may need to declair all possible flags that will be hit. I've just confirmed this code as working in a test project using your given string value in the question. Let me know if it meets your requirements. When declaring multiple flags in a single parameter use | instead of &

edit: http://msdn.microsoft.com/en-us/library/cc138362.aspx Find an explination of the different bitwise operators under the "Enumeration Types as Bit Flags" heading (That was harder to find than i thought.)

like image 197
Skintkingle Avatar answered Nov 15 '22 18:11

Skintkingle


I would use TryParse instead of Parse, in order to avoid exceptions, i.e.:

long xi;
if (long.TryParse(numberString, System.Globalization.NumberStyles.AllowThousands | System.Globalization.NumberStyles.AllowLeadingSign, null, out xi))
    {
        // OK, use xi
    }
    else
    {
        // not valid string, xi is 0
    }
like image 37
Francesco Baruchelli Avatar answered Nov 15 '22 16:11

Francesco Baruchelli