A little confused about NSDecimalNumber?

68 Views Asked by At

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"


1

There are 1 best solutions below

3
On BEST ANSWER

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