使用float表示货币值的结果不正确

Mat*_*sen 2 objective-c ios

如果我使用以下代码:

- (NSString*)formatToCurrency:(float)inFloat {
  NSNumberFormatter *currencyFormatter = [[[NSNumberFormatter alloc] init] autorelease];
  [currencyFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
  [currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
  [currencyFormatter setMaximumFractionDigits:2];
  [currencyFormatter setLocale:[NSLocale currentLocale]];

  NSNumber *x = [NSNumber numberWithFloat:inFloat];
  return [NSString stringWithFormat:@"  %@", [currencyFormatter stringFromNumber:x]];
}
Run Code Online (Sandbox Code Playgroud)

然后在调用代码时通过203500,我收到输出:$ 203,500.02.

我很想听听有关正在发生的事情的一些想法.

谢谢,

马特

编辑:当我用调试器查看时,XCode报告了203500,但是当我将浮点数转换为NSString时,它也会显示203500.018.这意味着问题出在浮点数而不是NSNumberFormatter中.

Vik*_*ica 6

您正在使用float创建NSNumber.浮点数总是会出现舍入误差

每个计算机科学家应该知道的浮点运算

您应该熟悉NSDecimals和NSDecimalNumbers

Cocoa是我的GF:不要和NSDecimalNumber一样懒(跟我一样)

  • 对于`NSDecimal`为+1,但如果不允许小数分数,则更好的解决方案是将美元金额编码为美分,并使用整数值类型来存储它 (3认同)