Obtaining an NSDecimalNumber from a locale specific string?

前端 未结 4 1925
谎友^
谎友^ 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

    Years later:

    +(NSDecimalNumber *)decimalNumberWithString:(NSString *)numericString in NSDecimalNumber.

    0 讨论(0)
  • 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).

    0 讨论(0)
  • 2020-11-30 05:04

    Based on Boaz Stuller's answer, I logged a bug to Apple for this issue. Until that is resolved, here are the workarounds I've decided upon as being the best approach to take. These workarounds simply rely upon rounding the decimal number to the appropriate precision, which is a simple approach that can supplement your existing code (rather than switching from formatters to scanners).

    General Numbers

    Essentially, I'm just rounding the number based on rules that make sense for my situation. So, YMMV depending on the precision you support.

    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
    [formatter setGeneratesDecimalNumbers:TRUE];
    
    NSString *s = @"0.07";
    
    // Create your desired rounding behavior that is appropriate for your situation
    NSDecimalNumberHandler *roundingBehavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:2 raiseOnExactness:FALSE raiseOnOverflow:TRUE raiseOnUnderflow:TRUE raiseOnDivideByZero:TRUE]; 
    
    NSDecimalNumber *decimalNumber = [formatter numberFromString:s];
    NSDecimalNumber *roundedDecimalNumber = [decimalNumber decimalNumberByRoundingAccordingToBehavior:roundingBehavior];
    
    NSLog([decimalNumber stringValue]); // prints 0.07000000000000001
    NSLog([roundedDecimalNumber stringValue]); // prints 0.07
    

    Currencies

    Handling currencies (which is the actual problem I'm trying to solve) is just a slight variation on handling general numbers. The key is that the scale of the rounding behavior is determined by the maximum fractional digits used by the locale's currency.

    NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];
    [currencyFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
    [currencyFormatter setGeneratesDecimalNumbers:TRUE];
    [currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
    
    // Here is the key: use the maximum fractional digits of the currency as the scale
    int currencyScale = [currencyFormatter maximumFractionDigits];
    
    NSDecimalNumberHandler *roundingBehavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:currencyScale raiseOnExactness:FALSE raiseOnOverflow:TRUE raiseOnUnderflow:TRUE raiseOnDivideByZero:TRUE]; 
    
    // image s is some locale specific currency string (eg, $0.07 or €0.07)
    NSDecimalNumber *decimalNumber = (NSDecimalNumber*)[currencyFormatter numberFromString:s];
    NSDecimalNumber *roundedDecimalNumber = [decimalNumber decimalNumberByRoundingAccordingToBehavior:roundingBehavior];
    
    NSLog([decimalNumber stringValue]); // prints 0.07000000000000001
    NSLog([roundedDecimalNumber stringValue]); // prints 0.07
    
    0 讨论(0)
  • 2020-11-30 05:04

    See also Best way to store currency values in C++

    The best way to handle currency is to use an integer value for the smallest unit of the currency, i.e. cents for dollars/euros, etc. You'll avoid any floating point related precision errors in your code.

    With that in mind, the best way to parse strings containing a currency value is to do it manually (with a configurable decimal point character). Split the string at the decimal point, and parse both the first and second part as integer values. Then use construct your combined value from those.

    0 讨论(0)
提交回复
热议问题