NSDecimalNumber 不是应该能够进行以 10 为基数的算术吗?

发布于 2024-12-21 05:12:10 字数 404 浏览 2 评论 0原文

NSDecimalNumber *minVal = [NSDecimalNumber decimalNumberWithString:@"0.0"];
NSDecimalNumber *maxVal = [NSDecimalNumber decimalNumberWithString:@"111.1"];
NSDecimalNumber *valRange = [maxVal decimalNumberBySubtracting:minVal];
CGFloat floatRange = [valRange floatValue];
NSLog(@"%f", floatRange); //prints 111.099998

难道 NSDecimalNumber 不应该能够正确地进行以 10 为基数的算术吗?

NSDecimalNumber *minVal = [NSDecimalNumber decimalNumberWithString:@"0.0"];
NSDecimalNumber *maxVal = [NSDecimalNumber decimalNumberWithString:@"111.1"];
NSDecimalNumber *valRange = [maxVal decimalNumberBySubtracting:minVal];
CGFloat floatRange = [valRange floatValue];
NSLog(@"%f", floatRange); //prints 111.099998

Isn't NSDecimalNumber supposed to be able to do base-10 arithmetic correctly?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

一萌ing 2024-12-28 05:12:10

是的,NSDecimalNumber 以 10 为基数进行运算,但 CGFloat 则不然。

Yes, NSDecimalNumber operates in base-10, but CGFloat doesn't.

剑心龙吟 2024-12-28 05:12:10

是的,NSDecimalNumber 是以 10 为基数的。

转换为浮点类型会降低准确性。在他们的例子中,因为示例只使用了 NSLog 只是 NSLogNSDecimalNumber:

NSDecimalNumber *minVal = [NSDecimalNumber decimalNumberWithString:@"0.0"];
NSDecimalNumber *maxVal = [NSDecimalNumber decimalNumberWithString:@"111.1"];
NSDecimalNumber *valRange = [maxVal decimalNumberBySubtracting:minVal];
CGFloat floatRange = [valRange floatValue];
NSLog(@"floatRange: %f", floatRange);
NSLog(@"valRange: %@", valRange);

NSLog 输出:

floatRange: 111.099998
valRange: 111.1

Yes, NSDecimalNumber is base-10.

Converting to a floating point type will can loose accuracy. In their case since the example just used NSLog just NSLog the NSDecimalNumber:

NSDecimalNumber *minVal = [NSDecimalNumber decimalNumberWithString:@"0.0"];
NSDecimalNumber *maxVal = [NSDecimalNumber decimalNumberWithString:@"111.1"];
NSDecimalNumber *valRange = [maxVal decimalNumberBySubtracting:minVal];
CGFloat floatRange = [valRange floatValue];
NSLog(@"floatRange: %f", floatRange);
NSLog(@"valRange: %@", valRange);

NSLog output:

floatRange: 111.099998
valRange: 111.1
命硬 2024-12-28 05:12:10

好的,只要这样做,CGFloat aNumber = 111.1; 就会在调试器中显示为 111.099998甚至在对其执行任何操作之前。因此,当将其分配给不太精确的数据类型时,无论稍后发生任何算术运算,精度都会丢失。

OK, just doing that CGFloat aNumber = 111.1; shows as 111.099998 in the debugger, even before any operation has been performed on it. Therefore the precision is lost right when it is assigned to the less precise data type, regardless of any arithmetic operations occurring later.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文