目标 c 中的 Round Double 值

问题描述

如何在目标 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;
}

时间过去

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

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

这并没有直接解决复杂性,并且在某些情况下也会失败,但它对完成工作大有帮助,例如现在输出读取

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...