如何在Objective-C中将2位小数舍入为十进制

时间:2013-03-15 09:53:12

标签: ios objective-c

让我知道如何在Objective-C中将小数点数舍入为2位小数。

我想这样做。 (句子后面的所有数字都是浮动值)

•round

10.118 => 10.12

10.114 => 10.11

•ceil

10.118 => 10.12

•floor

10.114 => 10.11

感谢您查看我的问题。

3 个答案:

答案 0 :(得分:31)

如果您确实需要对数字进行舍入,而不仅仅是在呈现时:

float roundToN(float num, int decimals)
{
    int tenpow = 1;
    for (; decimals; tenpow *= 10, decimals--);
    return round(tenpow * num) / tenpow;
}

或者总是小数点后两位:

float roundToTwo(float num)
{
    return round(100 * num) / 100;
}

答案 1 :(得分:13)

您可以使用以下代码将其格式化为两位小数

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
formatter.setMaximumFractionDigits = 2;
formatter.setRoundingMode = NSNumberFormatterRoundUp;

NSString *numberString = [formatter stringFromNumber:@(10.358)];
NSLog(@"Result %@",numberString); // Result 10.36

答案 2 :(得分:0)

float roundedFloat = (int)(sourceFloat * 100 + 0.5) / 100.0;