繁体   English   中英

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 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 相反,它只会将格式应用于 output 作为字符串。

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'

最后但同样重要的是,您可以对 C 执行与对 swift 相同的操作。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM