本文介绍了将双精度值舍入为小数点后2位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个双精度值为22.368511
我想舍入到2个小数位。即它应该返回22.37
I have a double value as 22.368511I want to round it to 2 decimal places. i.e. it should return 22.37
我该如何做?
推荐答案
在大多数语言中,格式为
As in most languages the format is
%.2f
您可以查看更多示例此处
you can see more examples here
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]]);
}
2010-08-22 15:04:10.614 a.out[6954:903] 25.34
2010-08-22 15:04:10.616 a.out[6954:903] 25.3
2010-08-22 15:04:10.617 a.out[6954:903] 25
这篇关于将双精度值舍入为小数点后2位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!