本文介绍了将双精度值舍入到小数点后两位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个双精度值 22.368511我想把它四舍五入到小数点后两位.即它应该返回 22.37
我该怎么做?
解决方案
与大多数语言一样,格式是
%.2f
您可以在此处查看更多示例
编辑:如果您担心 25.00 时点的显示,我也得到了这个
{NSNumberFormatter *fmt = [[NSNumberFormatter alloc] init];[fmt setPositiveFormat:@"0.##"];NSLog(@"%@", [fmt stringFromNumber:[NSNumber numberWithFloat:25.342]]);NSLog(@"%@", [fmt stringFromNumber:[NSNumber numberWithFloat:25.3]]);NSLog(@"%@", [fmt stringFromNumber:[NSNumber numberWithFloat:25.0]]);}
2010-08-22 15:04:10.614 a.out[6954:903] 25.342010-08-22 15:04:10.616 a.out[6954:903] 25.32010-08-22 15:04:10.617 a.out[6954:903] 25
I have a double value as 22.368511I want to round it to 2 decimal places. i.e. it should return 22.37
How can I do that?
解决方案
As in most languages the format is
%.2f
you can see more examples here
Edit: I also got this if your concerned about the display of the point in cases of 25.00
{
NSNumberFormatter *fmt = [[NSNumberFormatter alloc] init];
[fmt setPositiveFormat:@"0.##"];
NSLog(@"%@", [fmt stringFromNumber:[NSNumber numberWithFloat:25.342]]);
NSLog(@"%@", [fmt stringFromNumber:[NSNumber numberWithFloat:25.3]]);
NSLog(@"%@", [fmt stringFromNumber:[NSNumber numberWithFloat:25.0]]);
}
这篇关于将双精度值舍入到小数点后两位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!