Objective-c convert Long and float to String

 ̄綄美尐妖づ 提交于 2019-11-30 07:58:08

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];

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

You should use NSNumberFormatter eg:

    NSNumberFormatter * nFormatter = [[NSNumberFormatter alloc] init];
    [nFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
    NSNumber *num = [nFormatter numberFromString:@"12345678.1234"];
    [nFormatter release];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!