Cocoa touch 有没有一种简单的方法可以使用标准Cocoa库进行分层硬币舍入?
。为了使现金交易能够以5美分的分辨率进行处理,实施了以下四舍五入政策: 无论是现金交易还是非现金交易,商品和服务税(GST)或统一销售税(HST)的计算将继续按便士计算,并计入价格。只有交易的现金支付总额才会四舍五入 从 也就是说,所有计算都应尽可能准确,并最终使用标准的“断开连接”来实现百分之一百的分辨率,但当需要支付现金时,需要进一步四舍五入到最接近的五分之一 对于国际化,我需要实现这一点。我还想在其他地方重复使用这一点,比如说,最终成本四舍五入到10、25等。我如何在iOS中使用Cocoa touch 有没有一种简单的方法可以使用标准Cocoa库进行分层硬币舍入?,cocoa-touch,internationalization,nsdecimalnumber,Cocoa Touch,Internationalization,Nsdecimalnumber,。为了使现金交易能够以5美分的分辨率进行处理,实施了以下四舍五入政策: 无论是现金交易还是非现金交易,商品和服务税(GST)或统一销售税(HST)的计算将继续按便士计算,并计入价格。只有交易的现金支付总额才会四舍五入 从 也就是说,所有计算都应尽可能准确,并最终使用标准的“断开连接”来实现百分之一百的分辨率,但当需要支付现金时,需要进一步四舍五入到最接近的五分之一 对于国际化,我需要实现这一点。我还想在其他地方重复使用这一点,比如说,最终成本四舍五入到10、25等。我如何在iOS中使用NSDec
NSDecimalNumber
s?
如果在Obj-C上能像这样工作,我会很高兴的:
finalCost = [total roundWithResolution:@0.05];
或者在Swift中:
finalCost = total.roundWithResolution(0.05);
为了消除上述任何歧义,这是在使用“向上取整”平局突破已取整到第一百位后的行为: 5¢
- 0.98至1.02美元→ $1.00
- $1.03至$1.07→ $1.05
- 1.08至1.10美元→ $1.10
- 等等
- 0.96至1.05美元→ $1.00
- $1.06至$1.15→ $1.10
- 等等
- 0.88至1.12美元→ $1.00
- 1.13至1.37美元→ $1.25
- 1.38至1.62美元→ $1.50
- 1.63至1.87美元→ $1.75
- 1.88至2.12美元→ $二点
- 等等
- 花了我一个晚上的时间四处询问并测试解决方案,但我最终得出了以下结论:
@implementation NSDecimalNumber (RoundWithResolution)
- (NSDecimalNumber *)roundWithResolution:(NSDecimalNumber *)resolution
{
NSDecimalNumber *step1 = [self decimalNumberByDividingBy:resolution];
NSDecimalNumber *step2 = [step1 round:0];
NSDecimalNumber *step3 = [step2 decimalNumberByMultiplyingBy:resolution];
NSDecimalNumber *step4 = [step3 round:2];
return step4;
}
- (NSDecimalNumber *)round:(NSUInteger)decimalPlaces
{
NSNumberFormatter *formatter = [NSNumberFormatter new];
formatter.roundingMode = NSNumberFormatterRoundHalfUp;
formatter.numberStyle = NSNumberFormatterNoStyle;
formatter.maximumFractionDigits = decimalPlaces;
return [NSDecimalNumber decimalNumberWithString:[formatter stringFromNumber:self]];
}
@end
这是基于kccu、米洛·布兰特和埃里克·托尔斯:
花了我一个晚上的时间四处询问并测试解决方案,但我最终得出了以下结论:
@implementation NSDecimalNumber (RoundWithResolution)
- (NSDecimalNumber *)roundWithResolution:(NSDecimalNumber *)resolution
{
NSDecimalNumber *step1 = [self decimalNumberByDividingBy:resolution];
NSDecimalNumber *step2 = [step1 round:0];
NSDecimalNumber *step3 = [step2 decimalNumberByMultiplyingBy:resolution];
NSDecimalNumber *step4 = [step3 round:2];
return step4;
}
- (NSDecimalNumber *)round:(NSUInteger)decimalPlaces
{
NSNumberFormatter *formatter = [NSNumberFormatter new];
formatter.roundingMode = NSNumberFormatterRoundHalfUp;
formatter.numberStyle = NSNumberFormatterNoStyle;
formatter.maximumFractionDigits = decimalPlaces;
return [NSDecimalNumber decimalNumberWithString:[formatter stringFromNumber:self]];
}
@end
这是基于kccu、米洛·布兰特和埃里克·托尔斯:
“现金支付”部分的四舍五入方法是什么?(请参阅)@bgp标准,四舍五入。@bgp编辑为更清晰不确定,但您是否查看了NSDecimalNumberHandler?@bgp这似乎不符合我的需要。如果您认为可以,请在回答中详细说明!对“现金支付”部分的四舍五入方法是什么?(请参阅)@bgp标准,对半取整。@bgp编辑为更清晰不确定,但您是否查看了NSDecimalNumberHandler?@bgp这似乎不符合我的要求。如果您认为可以,请在回答中详细说明!