Objective-c convert Long and float to String

回眸只為那壹抹淺笑 提交于 2019-11-29 10:49:11

问题


I need to convert two numbers to string in Objective-C.

One is a long number and the other is a float.

I searched on the internet for a solution and everyone uses stringWithFormat: but I can't make it work.

I try

NSString *myString = [NSString stringWithFormat: @"%f", floatValue]

for 12345678.1234 and get "12345678.00000" as output

and

NSString *myString = [NSString stringWithFormat: @"%d", longValue]

Can somebody show me how to use stringWithFormat: correctly?


回答1:


This article discusses how to use various formatting strings to convert numbers/objects into NSString instances:

String Programming Guide: Formatting String Objects

Which use the formats specified here:

String Programming Guide: String Format Specifiers

For your float, you'd want:

[NSString stringWithFormat:@"%1.6f", floatValue]

And for your long:

[NSString stringWithFormat:@"%ld", longValue] // Use %lu for unsigned longs

But honestly, it's sometimes easier to just use the NSNumber class:

[[NSNumber numberWithFloat:floatValue] stringValue];
[[NSNumber numberWithLong:longValue] stringValue];



回答2:


floatValue has to be a double. At least this compiles correctly and does what is expected on my machine Floats can only store about 8 decimal digits and your number 12345678.1234 requires more precision than that, hence only about the 8 most significant digit are stored in a float.

double floatValue = 12345678.1234;
NSString *myString = [NSString stringWithFormat: @"%f", floatValue];

results in

2011-11-04 11:40:26.295 Test basic command line[7886:130b] floatValue = 12345678.123400



回答3:


You should use NSNumberFormatter eg:

    NSNumberFormatter * nFormatter = [[NSNumberFormatter alloc] init];
    [nFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
    NSNumber *num = [nFormatter numberFromString:@"12345678.1234"];
    [nFormatter release];


来源:https://stackoverflow.com/questions/8011706/objective-c-convert-long-and-float-to-string

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