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

时间的流逝

事实上,我能看到很多麻烦。不确定这是否是困扰您的问题,但例如,在输出中显示
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

相关内容

最新更新