ios 如何在Objective-C中四舍五入为2位小数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15429221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 22:44:54  来源:igfitidea点击:

How to round decimal for 2 decimal places in Objective-C

iosobjective-c

提问by Takuya Takahashi

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

让我知道如何在 Objective-C 中将小数点四舍五入到小数点后两位。

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

? 细胞

10.118 => 10.12

10.118 => 10.12

? floor

? 地面

10.114 => 10.11

10.114 => 10.11

Thanks for checking my question.

感谢您检查我的问题。

回答by

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;
}

回答by Suhaiyl

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

回答by Gobra

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