如何让 NSDecimal 舍入到最接近的整数值?

How can I get NSDecimal to round to the nearest integer value?

我正在使用 NSDecimal,因为我必须为我的应用程序存储非常大的值。我希望能够使用 NSDecimalDivide 函数来划分两个 NSDecimals 并将结果四舍五入到最接近的整数。

    NSDecimal testOne = [[NSDecimalNumber decimalNumberWithString:@"1064"] decimalValue];
    NSDecimal cost = [[NSDecimalNumber    decimalNumberWithString:@"10"]decimalValue];
    NSDecimal value;
    NSDecimalDivide(&value, &testOne, &cost, NSRoundDown);
    NSString *string = NSDecimalString(&value, _usLocale);
    NSLog(@"Here is the cost%@",string);

这个输出为 106.4 我希望它输出 106。有谁知道如何将 NSDecimal 数字四舍五入为整数值?

将 NSDecimal 封装为 NSDecimalNumber 并使用 decimalNumberByRoundingAccordingToBehavior:。这使您可以指定所需的精确舍入 behavior

一种可能的方法是使用 NSDecimalNumberHandler 并将 scale 设置为 0

NSDecimalNumber *number1 = [NSDecimalNumber decimalNumberWithString:@"1064"];
NSDecimalNumber *number2 = [NSDecimalNumber decimalNumberWithString:@"10"];

NSDecimalNumberHandler *behavior = [[NSDecimalNumberHandler alloc] initWithRoundingMode:NSRoundDown
                                                                                  scale:0
                                                                       raiseOnExactness:NO
                                                                        raiseOnOverflow:NO
                                                                       raiseOnUnderflow:NO
                                                                    raiseOnDivideByZero:YES];

NSDecimalNumber *result = [number1 decimalNumberByDividingBy:number2 withBehavior:behavior];

NSLog(@"Here is the cost %@", result);

请注意,我根本没有使用原语 NSDecimal,我也会建议你这样做。

但是,如果您想直接使用 NSDecimal,可以使用方便的 NSDecimalRound 函数。