Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert float value to NSString

Tags:

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.

like image 975
Alexandre Ouicher Avatar asked Jan 23 '12 16:01

Alexandre Ouicher


People also ask

Can you convert float to String?

The Float. toString() method can also be used to convert the float value to a String. The toString() is the static method of the Float class.

Can we convert float to String in java?

We can convert float to String in java using String. valueOf() and Float. toString() methods.


1 Answers

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.

like image 68
taskinoor Avatar answered Oct 21 '22 20:10

taskinoor