使浮点数仅显示两位小数。

18 浏览
0 Comments

使浮点数仅显示两位小数。

我有一个 float 类型的数值为 25.00,但当我在屏幕上输出它时,它显示为 25.0000000

我该如何仅显示两位小数呢?

admin 更改状态以发布 2023年5月21日
0
0 Comments

以下是一些更正-

//for 3145.559706


Swift 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"


Obj-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"

等等...

0
0 Comments

这不是数字如何存储的问题,而是您如何显示它的问题。在将其转换为字符串时,您必须将其舍入到所需的精度,即您的情况下是两位小数。

例如:

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

%.02f 告诉格式化程序你将格式化一个浮点数 (%f),它应该舍入到两位数,并应该用 0 进行填充。

例如:

%f = 25.000000
%.f = 25
%.02f = 25.00

0