将浮点值转换为NSString
问题描述:
您知道如何将浮点值转换为nsstring值,因为在我的代码中出现错误.
Do you know how can i convert float value to nsstring value because with my code, there is an error.
我的代码:
- (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];
//....
}
错误:
EXC_BAD ACCESS for NSString *tx_nb_demande_portabilite_st = [NSString stringWithFormat:@"%@", tx_nb_demande_portabilite];
谢谢您的帮助.
答
您需要将%f
格式说明符用于浮点,而不是%@
.
You need to use %f
format specifier for float, not %@
.
NSString *str = [NSString stringWithFormat:@"%f", myFloat];
要使用小数点后的特定位数,请使用%.nf
,其中n是小数点后的位数.
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使用C printf
样式格式.请检查 printf手册页,以获取所有其他可能的格式.
Obj-C uses C printf
style formatting. Please check printf man page for all other possible formatting.