objective-cdoublensdecimalnumbercgfloat

A little confused about NSDecimalNumber?


there are a short code

    NSString *numString = @"2128.123123";
    NSDecimalNumber *large = [NSDecimalNumber decimalNumberWithString:numString];
    NSDecimalNumberHandler *decimalHandler = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:2 raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:YES];
    NSDecimalNumber *fin = [large decimalNumberByRoundingAccordingToBehavior:decimalHandler];
    NSLog(@"%@",fin);

seem ok, print "2128.12".

.....

but you can try numString = @"78.991";

NSLog(@"%@",fin)

print "78.98999999999999"....

why scale is invalid? expect "78.99"



Solution

  • fin is ok but NSLog calls doubleValue. In earlier versions of macOS, NSLog did call description which returns "78.99". Solution: NSLog(@"%@", fin.description).