使浮点数只显示两位小数 [英] Make a float only show two decimal places
本文介绍了使浮点数只显示两位小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 float
中有值 25.00
,但是当我在屏幕上打印它时它是 25.0000000
.
如何显示只有两位小数的值?
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.
例如:
NSString* formattedNumber = [NSString stringWithFormat:@"%.02f", myFloat];
%.02f
告诉格式化程序您将格式化一个浮点数 (%f
),并且应该四舍五入到两个位置,并且应该用 <填充code>0s.
%.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.
例如:
%f = 25.000000
%.f = 25
%.02f = 25.00
这篇关于使浮点数只显示两位小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文