使浮动只显示两位小数

我有一个float25.00 ,但是当我在屏幕上打印它是25.0000000
如何显示只有两位小数的值?


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

例如:

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

%.02f告诉格式化程序,您将格式化一个浮点数( %f ),并且应该舍入到两个地方,并且应该填充0秒。

例如:

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

这里有一些更正 -

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

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"

等等...


你也可以尝试使用NSNumberFormatter:

NSNumberFormatter* nf = [[[NSNumberFormatter alloc] init] autorelease];
nf.positiveFormat = @"0.##";
NSString* s = [nf stringFromNumber: [NSNumber numberWithFloat: myFloat]];

您可能还需要设置否定格式,但我认为它足够聪明,可以将其解决。

链接地址: http://www.djcxy.com/p/74371.html

上一篇: Make a float only show two decimal places

下一篇: jQuery & PHP: Calculate the sum and send it back to client