Note that there are some explanatory texts on larger screens.

plurals
  1. POObtaining an NSDecimalNumber from a locale specific string?
    text
    copied!<p>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 <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfNumberFormatting10_4.html" rel="noreferrer">examples I've seen thus far on the interwebs</a>, this is accomplished by using an NSNumberFormatter a la:</p> <pre><code>NSString *s = @"0.07"; NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; [formatter setFormatterBehavior:NSNumberFormatterBehavior10_4]; [formatter setGeneratesDecimalNumbers:YES]; NSDecimalNumber *decimalNumber = [formatter numberFromString:s]; NSLog([decimalNumber stringValue]); // prints 0.07000000000000001 </code></pre> <p>I'm using 10.4 mode (in addition to being recommended per the documentation, it is also the only mode available on the iPhone) but indicating to the formatter that I want to generate decimal numbers. Note that I've simplified my example (I'm actually dealing with currency strings). However, I'm obviously doing something wrong for it to return a value that illustrates the imprecision of floating point numbers.</p> <p>What is the correct method to convert a locale specific number string to an NSDecimalNumber?</p> <p>Edit: Note that my example is for simplicity. The question I'm asking also should relate to when you need to take a locale specific currency string and convert it to an NSDecimalNumber. Additionally, this can be expanded to a locale specific percentage string and convert it to a NSDecimalNumber.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload