How i can convert NSString to long value?

37,344

Solution 1

You can use NSString methods intValue longLongValue.

Solution 2

For a small number like this "100023", this is acceptable with 'longlongvalue'. However, if the number digits have more than >10 in which commonly regard as the use case for long value. Then, you will run in into this problem, such as:

String value "86200054340607012013"

do

@"86200054340607012013" integerValue or intValue 

you will produce this in the print statement

2147483647 

if you do

@"86200054340607012013" longlongvalue

you will produce this in the print statement

9223372036854775807

This works for me and print out the expected number.

NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber * myNumber = [f numberFromString:@"2394739287439284734723"];
NSLog(@"longlong: %llu", [myNumber longLongValue]);   

Solution 3

Use this:

    yourLong = [yourString longLongValue];

Solution 4

you can use the doubleValue Method to avoid lose of precision warnings

Share:
37,344
Ankit Vyas
Author by

Ankit Vyas

I am a Computer Engineer and Working as an iphone application Developer.

Updated on March 28, 2020

Comments

  • Ankit Vyas
    Ankit Vyas about 4 years

    I have one value 100023 and I have taken it in NSString.

    Now I want to pass this value in my web service which contains long parameter type so how can I convert string value to long.