将浮点值转换为NSString

Ale*_*her 15 objective-c

你知道我怎样才能将浮点值转换为nsstring值,因为我的代码存在错误.

我的代码:

- (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];
//....
}
Run Code Online (Sandbox Code Playgroud)

错误 :

EXC_BAD ACCESS for NSString *tx_nb_demande_portabilite_st = [NSString stringWithFormat:@"%@", tx_nb_demande_portabilite];
Run Code Online (Sandbox Code Playgroud)

谢谢您的帮助.

tas*_*oor 48

你需要使用%ffloat的格式说明符,而不是%@.

NSString *str = [NSString stringWithFormat:@"%f", myFloat];
Run Code Online (Sandbox Code Playgroud)

使用小数点后使用的特定位数,%.nf其中n是小数点后的位数.

// 3 digits after decimal point
NSString *str = [NSString stringWithFormat:@"%.3f", myFloat];
Run Code Online (Sandbox Code Playgroud)

Obj-C使用C printf样式格式.请检查printf手册页以获取所有其他可能的格式.