Get a long value from an NSString

那年仲夏 提交于 2019-12-14 01:54:21

问题


I need to get a long value from an NSString.

For example, I have this:

NSString *test = @"5437128";

and I need :

long myLong = 5437128;   

How I can get this long value from the NSString?

Thank you, it will help me!


回答1:


Use the NSScanner like in the following code:

  unsigned x;

[[NSScanner scannerWithString: s2] scanHexInt: &x];

when typing the scanHexInt stop at scan and see yourself which one you need - there are many possibilities to get values from strings....

You might want to use scanlonglong... having declared your variable as long




回答2:


long longVariable = [test longLongValue];  

See NSString documentation..




回答3:


use this code :

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
long number = [[numberFormatter numberFromString:string] longValue];
[numberFormatter release];



回答4:


i use the following in case you don't want to lose the fractions value of your number

double x =[stringValue doubleValue];

instead of

 double x = [stringValue  longLongValue];

if we assume that we have the following string value and we want to convert it to double we have 2 ways

NSString * stringValue = @"31.211529225111";
way #1 
    double x = [stringValue  longLongValue];
result will be  :  x = 31

way #2 
    double x =[stringValue doubleValue];
result will be  :  x = 31.211529225111001


来源:https://stackoverflow.com/questions/5751706/get-a-long-value-from-an-nsstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!