我有一个漂浮物,想要像这样圆:
1.31 = 1.30
1.34 = 1.30
1.37 = 1.35
1.39 = 1.35
我的(错误)代码:
float price = 1.3791;
float priceRounded = [[NSString stringWithFormat:@"%.2f",price]floatValue];
答案 0 :(得分:2)
您可以通过执行以下操作来消除stringWithFormat:
的使用:
float princeRounded = (long)(price * 20) / 20.0;
这将price
乘以20然后取整数结果(基本上向下舍入),然后将结果除以20,确保结果始终以.05
,.1
结束,.15
等。
请注意,这总是向下舍入到0.05或0.1,就像您在示例中所示。这与你的标题中的舍入到最接近的0.05或0.1不一样。
答案 1 :(得分:1)
你可以试试这个
float priceRounded = [[NSString stringWithFormat:@"%.2f",floor(price*20)/20]floatValue];