我在浮点数中有值25.00,但当我在屏幕上打印它时,它是25.0000000。 如何显示只有两位小数点后的值?
当前回答
使用NSNumberFormatter和maximumFractionDigits,如下所示:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.maximumFractionDigits = 2;
NSLog(@"%@", [formatter stringFromNumber:[NSNumber numberWithFloat:12.345]]);
你会得到12.35
其他回答
这里有一些更正
//for 3145.559706
斯威夫特3
let num: CGFloat = 3145.559706
print(String(format: "%f", num)) = 3145.559706
print(String(format: "%.f", num)) = 3145
print(String(format: "%.1f", num)) = 3145.6
print(String(format: "%.2f", num)) = 3145.56
print(String(format: "%.02f", num)) = 3145.56 // which is equal to @"%.2f"
print(String(format: "%.3f", num)) = 3145.560
print(String(format: "%.03f", num)) = 3145.560 // which is equal to @"%.3f"
卷-C
@"%f" = 3145.559706
@"%.f" = 3146
@"%.1f" = 3145.6
@"%.2f" = 3145.56
@"%.02f" = 3145.56 // which is equal to @"%.2f"
@"%.3f" = 3145.560
@"%.03f" = 3145.560 // which is equal to @"%.3f"
等等……
你也可以尝试使用NSNumberFormatter:
NSNumberFormatter* nf = [[[NSNumberFormatter alloc] init] autorelease];
nf.positiveFormat = @"0.##";
NSString* s = [nf stringFromNumber: [NSNumber numberWithFloat: myFloat]];
你可能还需要设置否定格式,但我认为解决这个问题已经足够聪明了。
在Swift语言中,如果你想要显示你需要这样使用它。要在UITextView中赋值double,例如:
let result = 23.954893
resultTextView.text = NSString(format:"%.2f", result)
如果你想在LOG中显示,就像objective-c使用NSLog()一样,那么在Swift语言中你可以这样做:
println(NSString(format:"%.2f", result))
在objective -c中,你想显示2个十进制数的浮点值,然后传递参数指示你想显示多少个小数点 例如0.02f将打印25.00 0.002f将打印25.000
在objective-c中,如果你正在处理常规字符数组(而不是指向NSString的指针),你也可以使用:
printf("%.02f", your_float_var);
OTOH,如果你想把这个值存储在一个char数组中,你可以使用:
sprintf(your_char_ptr, "%.02f", your_float_var);
推荐文章
- Xcode构建失败“架构x86_64未定义的符号”
- 动态改变UILabel的字体大小
- registerForRemoteNotificationTypes: iOS 8.0及以上版本不支持
- 新的自动引用计数机制是如何工作的?
- 如何测试对象在Objective-C中的类?
- 是否有可能禁用浮动头在UITableView与UITableViewStylePlain?
- 从Cocoa应用程序执行一个终端命令
- Swift编译器错误:“框架模块内的非模块化头”
- 从父iOS访问容器视图控制器
- 自定义dealloc和ARC (Objective-C)
- 调整UITableView的大小以适应内容
- 在代码中为UIButton设置一个图像
- UICollectionView中的单元格间距
- 我如何在我的iOS应用程序中每n分钟得到一个后台位置更新?
- 如何显示有两个小数点后的浮点数?