如何在Objective-C中重复2位小数的十进制数[复制]

时间:2022-05-27 11:17:18

This question already has an answer here:

这个问题在这里已有答案:

Let me know how to round decimal for 2 decimal places in Objective-C.

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

I would like to do like this. (all of numbers following sentence is float value)

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

• round

•圆形

10.118 => 10.12

10.118 => 10.12

10.114 => 10.11

10.114 => 10.11

• ceil

•ceil

10.118 => 10.12

10.118 => 10.12

• floor

•地板

10.114 => 10.11

10.114 => 10.11

Thanks for checking my question.

谢谢你查看我的问题。

3 个解决方案

#1


30  

If you actually need the number to be rounded, and not just when presenting it:

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

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

Or always to two decimal places:

或者总是小数点后两位:

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

#2


10  

You can use the below code to format it to two decimal places

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

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

#3


0  

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

#1


30  

If you actually need the number to be rounded, and not just when presenting it:

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

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

Or always to two decimal places:

或者总是小数点后两位:

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

#2


10  

You can use the below code to format it to two decimal places

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

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

#3


0  

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