繁体   English   中英

目标 c 中的 Round Double 值

[英]Round Double value in objective c

如何在目标 c 中舍入双值,如果值为 1.66,则显示值为 1.55,如果计算更高,则缺少一个点值,这会产生影响?

self.priceLabel.text = [NSString stringWithFormat:@"%0.2f",totalPrice];

我已经使用了其他多种东西,包括格式化程序,但这个问题仍然存在

计算器的计算显示值如 293.76 但通过这种方式显示值 293.75 我需要该值为 293.76

这里有一些东西可以说明。

看起来都不错?? 问题是什么?

#import <Foundation/Foundation.h>

NSString * round02( double val )
{
    return [NSString stringWithFormat:@"%.2f", val];
}

int main(int argc, const char * argv[]) {
    @autoreleasepool
    {
        // insert code here...
        NSLog(@"Hello, World!");

        double x = 0;

        while ( x < 3 )
        {
            x += 0.001;
            NSLog ( @"Have %f becomes %@ and %@", x, round02( x ), round02( -x ) );
        }
    }

    return 0;
}

时间流逝

事实上,我可以看到很多麻烦。 不确定这是否是困扰您的问题,但例如在 output 中显示

2021-03-04 12:37:13.116147+0200 Rounding[15709:202740] Have 2.723000 becomes 2.72 and -2.72
2021-03-04 12:37:13.116210+0200 Rounding[15709:202740] Have 2.724000 becomes 2.72 and -2.72
2021-03-04 12:37:13.116316+0200 Rounding[15709:202740] Have 2.725000 becomes 2.72 and -2.72
2021-03-04 12:37:13.116383+0200 Rounding[15709:202740] Have 2.726000 becomes 2.73 and -2.73

最后的2.72应该是2.73 ,但是,这又是一个复杂的问题。 这是解决它的一种简单方法 - 添加一个容差,如下例所示。

NSString * round02( double val )
{
    double tol = 0.0005;

    if ( val >= 0 )
    {
        return [NSString stringWithFormat:@"%.2f", val + tol];
    }
    else
    {
        return [NSString stringWithFormat:@"%.2f", val - tol];
    }
}

这并不能直接解决复杂性,并且在某些情况下也会失败,但它将使 go 完成工作还有很长的路要走,例如现在 output 读取

2021-03-04 12:40:11.274826+0200 Rounding[15727:204617] Have 2.723000 becomes 2.72 and -2.72
2021-03-04 12:40:11.274941+0200 Rounding[15727:204617] Have 2.724000 becomes 2.72 and -2.72
2021-03-04 12:40:11.275016+0200 Rounding[15727:204617] Have 2.725000 becomes 2.73 and -2.73
2021-03-04 12:40:11.275096+0200 Rounding[15727:204617] Have 2.726000 becomes 2.73 and -2.73

暂无
暂无

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

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