Convert float value to NSString - objective-c

Do you know how can i convert float value to nsstring value because with my code, there is an error.
My Code :
- (float)percent:(float)a :(float)b{
return a / b * 100;
}
- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)objects {
// ....
float tx_nb_demande_portabilite = [self percent: [(NSNumber*) [stat nb_demande_portabilite] floatValue] :[(NSNumber*) [stat nb_users] floatValue]];
NSString *tx_nb_demande_portabilite_st = [NSString stringWithFormat:#"%#", tx_nb_demande_portabilite];
//....
}
The error :
EXC_BAD ACCESS for NSString *tx_nb_demande_portabilite_st = [NSString stringWithFormat:#"%#", tx_nb_demande_portabilite];
Thank you for your help.

You need to use %f format specifier for float, not %#.
NSString *str = [NSString stringWithFormat:#"%f", myFloat];
To use specific number of digits after decimal use %.nf where n is number of digits after decimal point.
// 3 digits after decimal point
NSString *str = [NSString stringWithFormat:#"%.3f", myFloat];
Obj-C uses C printf style formatting. Please check printf man page for all other possible formatting.

one more option:
NSString * str = [NSNumber numberWithFloat:value].stringValue;

#"%f" sounds like more appropriate format string for float.

[NSString stringWithFormat:#"%f", tx_nb_demande_portabilite];

A modern (and less verbose) approach would be:
NSString *str = #(myFloat).description;

Related

How to operate with float stored in dictionary in objective-c?

I have NSDictionary *results
When i do this:
self.tValue.text = [NSString stringWithFormat:#"%#", [results objectForKey:#"temperature"] + 273.15f];
I get the error:
Invalid operands for binary expression ('id _Nullable' and 'float')
Where I wrong?
The "float" stored in the NSDictionary is likely to be an NSNumber (or possibly an NSString) - it can't actually be a "float". You therefore need to get the "floatValue" of your NSDictionary value, do your addition, and then use the "float" string format.
Try the following:
self.tValue.text = [NSString stringWithFormat:#"%f", [results[#"temperature"] floatValue] + 273.15f];
you are adding float value with id object before doing that you must have convert temperature value into float Like:
CGFloat temperature = [[results objectForKey:#"temperature"] floatValue];
NSString *tValue = [NSString stringWithFormat:#"%f", temperature + 273.15f];

Objective-C: Double to NSString with x-many decimals

I know that I can cast a double to a NSString with a specific amount of decimals like so:
double myDouble = 123.456789;
NSString *myString = [NSString stringWithFormat:#"%.4g", myDouble];
But how can I replace the number "4" in this example with a int variable?
Something like this doesn't work:
double myDouble = 123.456789;
int precision = 4;
NSString *myString = [NSString stringWithFormat:#"%.%dg", myDouble, precision];
Consider using NSNumberFormatter:
double myDouble = 123.456789;
int precision = 4;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.minimumFractionDigits = precision;
formatter.maximumFractionDigits = precision;
NSString *myString = [formatter stringFromNumber:#(myDouble)];
Or, if you want this in scientific notation, you can alternatively specify something like:
formatter.numberStyle = NSNumberFormatterScientificStyle;
formatter.usesSignificantDigits = YES;
formatter.minimumSignificantDigits = precision;
formatter.maximumSignificantDigits = precision;
It just depends upon what precisely you're looking for.
This also has the virtue of also honoring the user's regional settings (e.g. if in Germany, the decimal separator is a comma, not a period).
If you need to force the locale setting (e.g. this is for creating something that will be exchanged with a web service that expects the data in a specified format), you can set the formatter's locale (e.g. [NSLocale localeWithLocaleIdentifier:#"en_US"]). But when presenting results in the user interface, you always want to honor the device's locale settings.
You can use asterisk in place of optional width and precision specifiers. And set them as arguments
double myDouble = 123.456789;
int width = 10;
int precision = 6;
NSString *s = [NSString stringWithFormat:#"%*.*g", width, precision, myDouble];
If you follow the links in the documentation for stringWithFormat you will discover the IEEE printf specification which describes the formats supported. That tells you that a field width or precision can be an * to indicate the actual value is supplied an an int argument, so what you want is:
NSString *myString = [NSString stringWithFormat:#"%.*g", intPrecision, myDouble];
double myDouble = 123.456789;
int precision = 4;
NSString *myString = [NSString stringWithFormat:#"%.*f", precision, myDouble];
NSLog(#"myString: '%#'", myString);
NSLog output:
myString: '123.4567'
This is by no means an optimal way of doing it, but it is a way.
You can do it in multiple steps
NSString *val = [NSString stringWithFormat: #"%d", 4];
NSString *head = [#"%." stringByAppendingString: val];
NSString *format = [head stringByAppendingString: #"g"];
NSString *result = [NSString stringWithFormat: format, 123.456789];
Or if you're really adventurous (for the sake of readability, don't EVER do this):
NSString *result = [NSString stringWithFormat: [[#"%." stringByAppendingString: [NSString stringWithFormat: #"%d", 4]] stringByAppendingString: #"g"], 123.456789];

Building string with float variables

How can i build a NSString variable consisting of string and float variables?
I assume i need to cast the floats to strings, but i cant see how this is done without creating alot of messy and ugly code.
I want to build something like this: String+ Float+ String+ Float
Thanks in advance.
That is not how Objective C works. In Java, you would use:
String yourString = string1 + " " + float1 + " " + string2 + " " + float2;
You cannot do the same in Objective C. To do something to the same effect, you would need:
NSString* yourString = [NSString stringWithFormat:#"%# %f %# %f", string1, float1, string2, float2];
This would result in the equivalent to the Java statement. %# indicates you want to format an object into the string, and %f indicates a floating point value.
When formatting floats in an NSString, you can specify how many decimal places you want to truncate to by placing a value in between the % and f. For example, to round the first float to 2 decimal places and the second one to 5 decimal places:
NSString* yourString = [NSString stringWithFormat:#"%# %.2f %# %.5f", string1, float1, string2, float2];
Try:
NSString *str = [NSString stringWithFormat:#"Some text %f some more text %f", floatVar, anotherFloat];
To answer the question as asked:
Assume:
NSString *str1 = #"string one";
NSString *str2 = #"string two";
float f1 = 1.0;
float f2 = 2.0;
NSString *answer = [NSString stringWithFormat:#"%#: %f. %#: %f.", str1, f1, str2, f2];
NSLog(#"%#", answer); // This will print "string one: 1.000000. string two: 2.000000."
float sampleFloatVariable = 50.0;
NSString *floatintoText = [NSString stringwithFormat:#"%f",sampleFloatVariable];
NSLog(#" float text %#",floatintoText);

Objective-C ASCII decimal integer to NSString conversion

How can I convert and ASCII decimal integer to an NSString in Objective-C? (Example: 36 to "$")
Thanks
Try this:
unichar asciiChar = 36;
NSString *stringWithAsciiChar = [NSString stringWithCharacters:&asciiChar length:1];
You can use the following:
NSString *s = [NSString stringWithFormat:#"%c", 36];
NSLog(#"%#", s); // $

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