使一个浮点只显示两位小数 [英] Make a float only show two decimal places
问题描述
我在 float
中的值 25.00
,但是当我在屏幕上打印时,它是 25.0000000
。
如何显示值只有两位小数?
这不是数字如何存储的问题,这是你如何显示它的问题。当把它转换成一个字符串时,你必须四舍五入到所需的精度,在你的情况下是两位小数。
例如:
NSString * formattedNumber = [NSString stringWithFormat:@%。02f,myFloat];
%。02f
告诉格式器你将格式化一个浮点数(%f
),并且应该舍入到两个地方,并且应该填充 0
例如:
%f = 25.000000
%.f = 25
%.02f = 25.00
I have the value 25.00
in a float
, but when I print it on screen it is 25.0000000
.
How can I display the value with only two decimal places?
It is not a matter of how the number is stored, it is a matter of how you are displaying it. When converting it to a string you must round to the desired precision, which in your case is two decimal places.
E.g.:
NSString* formattedNumber = [NSString stringWithFormat:@"%.02f", myFloat];
%.02f
tells the formatter that you will be formatting a float (%f
) and, that should be rounded to two places, and should be padded with 0
s.
E.g.:
%f = 25.000000
%.f = 25
%.02f = 25.00
这篇关于使一个浮点只显示两位小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!