Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-c convert Long and float to String

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?

like image 886
Mark Comix Avatar asked Nov 04 '11 15:11

Mark Comix


2 Answers

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]; 
like image 113
Craig Otis Avatar answered Oct 02 '22 23:10

Craig Otis


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
like image 34
simonpie Avatar answered Oct 03 '22 00:10

simonpie