-1

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"


  • Possible duplicate of [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – luk2302 Nov 14 '18 at 11:56
  • Works for me. I think we need an MCVE: https://stackoverflow.com/help/mcve – Ture Pålsson Nov 14 '18 at 12:15
  • @luk2302 you're missing the point of `NSDecimalNumber`. "An object for representing and performing arithmetic on base-10 numbers." – Willeke Nov 14 '18 at 13:02
  • @TurePålsson which version of macOS are you using? – Willeke Nov 14 '18 at 13:04
  • @Willeke I tested on Mojave, but I'm getting some linker warnings about stub files being out of sync (???) so it's possible that my system is somehow falling back to an older library... – Ture Pålsson Nov 14 '18 at 13:15
  • @luk2302 The linked thread is about *binary* floating point numbers. The whole point with `NSDecimalNumber` is, that it is decimal to prevent that problem. – Amin Negm-Awad Nov 14 '18 at 16:32

1 Answers1

2

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

Willeke
  • 14,578
  • 4
  • 19
  • 47
  • you mean, the fin value is "78.99"(although the initial value is "78.991")? NSLog makes it wrong? – Sunson_alone Nov 15 '18 at 05:29
  • and why "2128.123123" worked ok ,"78.991" not correct?╮( ̄▽ ̄"")╭ – Sunson_alone Nov 15 '18 at 05:39
  • `NSLog(@"%@",fin)` does the same as `NSLog(@"%0.16g", fin.doubleValue)`. This is the broken floating point math problem. Try `NSLog(@"%0.24g", fin.doubleValue)`. – Willeke Nov 15 '18 at 16:06