Objective-C 中的四舍五入

Round double in Objective-C

我想将 Objective-C 中的双精度四舍五入到小数点后一位。

在 Swift 中,我可以使用扩展名来完成:

public extension Double {
    /// Rounds the double to decimal places value
    func rounded(toPlaces places:Int) -> Double {
        let divisor = pow(10.0, Double(places))
        return (self * divisor).rounded() / divisor
    }
}

但是,显然你不能从 Objective-C 调用基元的扩展,所以我不能使用扩展。

我很乐意直接对 double 或作为字符串进行舍入,但是,以下都不起作用:

 double mydub = 122.12022222223322;
 NSString *axtstr = [NSString stringWithFormat:@"%2f", mydub]; //gives 122.120222

 double rounded = (round(mydub*10)) / 10.0; //gives 122.100000

如何转换 122.12022222223322;进入 122.1?

您需要在 %2f

之间加上一个小数

[NSString stringWithFormat:@"%.2f", mydub];

double mydouble = 122.12022222223322;
NSString *str = [NSString stringWithFormat:@"%.2f", mydouble];
// = @"122.12"

.. 不会舍入 mydouble。相反,它只会将格式应用于字符串输出。

double d = 122.49062222223322;
NSString *dStr = [NSString stringWithFormat:@"%.f %.1f %.2f %.3f", d, d, d, d];
// = @"122 122.5 122.49 122.491"

由于 Objective-C 与 C 共享语言规则,您可以安全地舍入

#include <math.h>

double rounded = round(mydouble);
// = 122.000000

当然你可以用你想要的乘法和除法来移动逗号。

double commashifted = round(mydouble*100.0)/100.0;
// = 122.120000;

如果您真的很想 Objective-C 类 在豪华版中做同样的事情,请查看 Foundation Framework 中的 'NSDecimal.h'

最后但并非最不重要的一点是,您可以像 swift 一样对 C 执行相同的操作。

double roundbycomma(int commata, double zahl) {
    double divisor = pow(10.0, commata);
    return round(zahl * divisor) / divisor;
}