为了账号安全,请及时绑定邮箱和手机立即绑定

使浮点数仅显示两位小数

使浮点数仅显示两位小数

狐的传说 2019-10-05 11:37:59
我有值25.00的float,但是当我打印在屏幕上它25.0000000。如何只显示两个小数位的值?
查看完整描述

3 回答

?
慕容708150

TA贡献1831条经验 获得超4个赞

这与数字的存储方式无关,而与显示方式有关。将其转换为字符串时,必须舍入到所需的精度,在您的情况下为两位小数。


例如:


NSString* formattedNumber = [NSString stringWithFormat:@"%.02f", myFloat];

%.02f告诉格式化程序您将格式化float(%f),并且应该将其四舍五入到两个位置,并用0s 填充。


例如:


%f = 25.000000

%.f = 25

%.02f = 25.00


查看完整回答
反对 回复 2019-10-05
?
白板的微信

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"

等等...


查看完整回答
反对 回复 2019-10-05
  • 3 回答
  • 0 关注
  • 822 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信