Obtaining an NSDecimalNumber from a locale specific string?

前端 未结 4 1935
谎友^
谎友^ 2020-11-30 04:07

I have some string s that is locale specific (eg, 0.01 or 0,01). I want to convert this string to a NSDecimalNumber. From the examples I\'ve seen thus far on the interwebs

4条回答
  •  执念已碎
    2020-11-30 04:59

    This seems to work:

    NSString *s = @"0.07";
    
    NSScanner* scanner = [NSScanner localizedScannerWithString:s];
    NSDecimal decimal;
    [scanner scanDecimal:&decimal];
    NSDecimalNumber *decimalNumber = [NSDecimalNumber decimalNumberWithDecimal:decimal];
    
    NSLog([decimalNumber stringValue]); // prints 0.07
    

    Also, file a bug on this. That's definitely not the correct behavior you're seeing there.

    Edit: Until Apple fixes this (and then every potential user updates to the fixed OSX version), you're probably going to have to roll your own parser using NSScanner or accept 'only' double accuracy for entered numbers. Unless you're planning to have the Pentagon budget in this app, I'd suggest the latter. Realistically, doubles are accurate to 14 decimal places, so at anything less than a trillion dollars, they'll be less than a penny off. I had to write my own date parsing routines based on NSDateFormatter for a project and I spent literally a month handling all the funny edge cases, (like how only Sweden has the day of week included in its long date).

提交回复
热议问题