3 回答
TA贡献1831条经验 获得超4个赞
这与数字的存储方式无关,而与显示方式有关。将其转换为字符串时,必须舍入到所需的精度,在您的情况下为两位小数。
例如:
NSString* formattedNumber = [NSString stringWithFormat:@"%.02f", myFloat];
%.02f告诉格式化程序您将格式化float(%f),并且应该将其四舍五入到两个位置,并用0s 填充。
例如:
%f = 25.000000
%.f = 25
%.02f = 25.00
TA贡献1883条经验 获得超3个赞
以下是一些更正-
//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"
对象
@"%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"
等等...
- 3 回答
- 0 关注
- 871 浏览
添加回答
举报