I'm having a serious dispute with NSNumberFormatter, and even after going through its extensive documentation, I haven't quite been able to wrap my head around a pretty straightforward issue that I encountered. I hope you guys can help me out.
What I have: an NSDecimalNumber representing a calculation result, displayed in a UITextField
What I need: Scientific notation of that result.
What I'm doing:
-(void)setScientificNotationForTextField:(UITextField*)tf Text:(NSString*)text {
NSString* textBefore = text;
// use scientific notation, i.e. NSNumberFormatterScientificStyle
NSNumberFormatter* formatter = [[NSNumberFormatter alloc] init];
//[formatter setGeneratesDecimalNumbers:YES];
[formatter setNumberStyle:NSNumberFormatterScientificStyle];
NSDecimalNumber* number = (NSDecimalNumber*)[formatter numberFromString:text];
tf.text = [number descriptionWithLocale:[[Utilities sharedUtilities] USLocale]];
NSString* textAfter = tf.text;
// DEBUG
NSLog(#"setScientificNotation | text before = %#, text after = %#", textBefore, textAfter);
[formatter release];
}
What happens:
A certain result may be 0.0099. textBefore will hold that correct value. If I don't tell the formatter to generate decimal numbers (commented out in the above snippet), it will create an NSNumber from an NSDecimalNumber which creates a false result and turns textAfterinto 0.009900000000000001 - a rounding error due to the reduced precision of NSNumber over NSDecimalNumber.
If I do tell the NumberFormatter to generate decimals, it will still create the wrong result . And what's more, where before it would insert the exponent notation (e.g. "1.23456e-10"), it would now generate (and thus display) the full decimal number, which is not what I want.
Again, I'd like to have the formatter use NSDecimalNumber so it doesn't falsify results plus have exponent notation where necessary.
Am I using the class wrong? Did I misinterpret the documentation? Can someone explain why this happens and how I can create the behavior I want? I will of course continue researching and update if I find anything.
You can't just cast an NSNumber to an NSDecimalNumber and expect it to work. If your number is not too complex, you can ditch NSNumberFormatter and try using this instead:
NSDecimalNumber* number = [NSDecimalNumber decimalNumberWithString:text];
That will give you an actual NSDecimalNumber instance, with its precision.
Unfortunately, setGeneratesDecimalNumbers: doesn't work properly. It's a known bug.
If your number is too complex to work with decimalNumberWithString:, you're probably out of luck with Apple's APIs. Your only options are either parsing the string manually into something NSDecimalNumber can understand or performing some post-processing on the imprecise value given to you by NSNumberFormatter.
Finally, if you really want a number in scientific notation, why not just use the number formatter you just used? Just call stringFromNumber: to get the formatted value.
Related
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, this is accomplished by using an NSNumberFormatter a la:
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
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.
What is the correct method to convert a locale specific number string to an NSDecimalNumber?
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.
Years later:
+(NSDecimalNumber *)decimalNumberWithString:(NSString *)numericString in NSDecimalNumber.
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
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).
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.
I have a value being stored as an NSDecimalNumber and when I convert it to a double it's losing precision.
For the current piece of data I'm debugging against, the value is 0.2676655. When I send it a doubleValue message, I get 0.267665. It's truncating instead of rounding and this is wreaking havoc with some code that uses hashes to detect data changes for a syncing operation.
The NSDecimalNumber instance comes from a third-party framework so I can't just replace it with a primitive double. Ultimately it gets inserted into an NSMutableString so I'm after a string representation, however it needs to be passed through a format specifier of "%.6lf", basically I need six digits after the decimal so it looks like 0.267666.
How can I accomplish this without losing precision? If there's a good way to format the NSDecimalNumber without converting to a double that will work as well.
The NSDecimalNumber instance comes from a third-party framework so I
can't just replace it with a primitive double.
Yes you can. NSDecimalNumber is an immutable subclass of NSNumber, which is a little too helpful when it comes to conversion:
double myDub = [NSDecimalNumber decimalNumberWithDecimal:[[NSNumber numberWithDouble:((double)0.2676655)] doubleValue]];
Ultimately it gets inserted into an NSMutableString so I'm after a
string representation, however it needs to be passed through a format
specifier of "%.6lf", basically I need six digits after the decimal so
it looks like 0.267666.
Double precision unfortunately does not round, but getting a string value that's off by one-millionth is not that big of a deal (I hope):
NSDecimalNumber *num = [NSDecimalNumber decimalNumberWithDecimal:[[NSNumber numberWithDouble:((double)0.2676655)] decimalValue]];
NSString *numString = [NSString stringWithFormat:#"%.6lf", [num doubleValue]];
NSLog(#"%#",numString);
I think that your are on a wrong path and somewhere lost in what to do.
First of all, keep in mind that in objective-c lond double is not supported, so you might better want to use something like %f instead of %lf.
[to be found in the documentation library under "Type encodings" of the objective c runtime programming guide]
Then I would rather expect that the value is show as being truncated, as the doubleValue returns an approximate value but the range you are using is still within the correct range.
You should use a simple formatter instead of moving numbers around, like:
// first line as an example for your real value
NSDecimalNumber *value = [NSDecimalNumber decimalNumberWithString:#"0.2676655"];
NSNumberFormatter *numFmt = [[NSNumberFormatter alloc] init];
[numFmt setMaximumFractionDigits:6];
[numFmt setMinimumFractionDigits:6];
[numFmt setMinimumIntegerDigits:1];
NSLog(#"Formatted number %#",[numFmt stringFromNumber:value]);
This has another benefit of using a locale aware formatter if desired. The result of the number formatter is the desired string.
I'm using NSNumberFormatter to format float values as integer strings, i.e. omitting the fractional part. I find it odd, that numbers in range (-0.5, 0) *open interval end up as -0. As this value will be displayed to the user, I think that negative zero is not appropriate. I have experimented with various combinations of numberStyle and roundingMode without success.
Is there a way to configure the NSNumberFormatter to output them as 0, or do I have to resort to manual correction for that range?
I had to do correct this myself. I am using the NSNumberFormatter to display temperature with default numberStyle — NSNumberFormatterNoStyle which rounds the numbers to the whole integer, roundingMode set to NSNumberFormatterRoundHalfUp. In the end I did intercept the values in problematic range and round it myself:
- (NSString *)temperature:(NSNumber *)temperature
{
float f = [temperature floatValue];
if (f < 0 && f > -0.5)
temperature = [NSNumber numberWithLong:lround(f)];
return [self.temperatureFormatter stringFromNumber:temperature];
}
No, there is no way to configure it to do that.
In "10.4 mode", NSNumberFormatter basically just wraps CFNumberFormatter (although it's not a direct toll-free-bridged wrapping). You can look at the list of Number Formatter Property Keys and it's pretty clear that there's nothing that will do what you want. (It may be possible in "10.0" mode; it would take a bit of trial and error to find out. But I doubt you want to use that.)
So pre-rounding (as Justin Boo suggests) is probably your best option.
You could, of course, post-process instead. Exactly what you want to do probably depends on whether you want to also render -0.00 as 0.00, what you want to happen for localizations that don't use "-0", etc. The simplest case would be as simple as this:
#interface NSNumberFormatter (NegativeZero)
- (NSString *)stringFromNumberNoNegativeZero:(NSNumber *)number;
#end
#implementation NSNumberFormatter (NegativeZero)
- (NSString *)stringFromNumberNoNegativeZero:(NSNumber *)number {
NSString *s = [self stringFromNumber:number];
if ([s isEqualToString:#"-0"]) return #"0";
return s;
}
#end
But if you want anything more complicated, it'll get more complicated.
I have a class holding various types of numeric values. Within this class I have a couple of helper methods that are used to output descriptor text for display within my application.
This descriptor text should always appear as an integer or float, depending on the definition of the particular instance.
The class has a property, DecimalWidth, that I use to determine how many decimals to display. I need help writing a line of code that displays the numeric value, but with a fixed number of decimals, (0 is a possibility, and in such a case the value should be displayed as an integer.)
I am aware that I can could return a value like [NSString stringWithFormat:#"%.02f", self.Value] but my problem is that I need to replace the '2' in the format string with the value of DecimalWidth.
I can think of couple ways of solving this problem. I could concat a string together and that is as the format string for the outputted string line. Or, I could make a format string within a format string.
These solutions sound hideous and seem rather inefficient, but maybe these are the best options that I have.
Is there an elegant way of constructing a dynamic formatting string where the output is a fixed decimal width number but the specified decimal width is dynamic?
That doesn't sound hideous or inefficient to me.
[NSString stringWithFormat:[NSString stringWithFormat:#"%%.%df", DecimalWidth], self.Value]
In fact I think it is rather elegant.
However one solution for the problem is definitely question suggested by #lulius caesar,
But one good way is also using NSNumberFormatter. Below is a sample code you can use to generate decimal values with fixed decimal number
NSNumberFormatter *numberFormatter=[[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setMinimumFractionDigits:DecimalWidth];
[numberFormatter setMaximumFractionDigits:DecimalWidth];
NSString * decimalString = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:self.value]]]
This is my main:
int x=0;
NSString *new=[[NSString alloc]initWithString:#"9+4"];
x=[new intValue];
NSLog(#"hi %i",x);
This results in 9.. .since giving the intValue of a string will read only numbers and stops when the character is not a digit.
So how can i print the result of my string and get a 13 instead??
Actually, NSExpression was made just for this:
NSExpression *expression = [NSExpression expressionWithFormat:#"9+4"];
// result is a NSNumber
id result = [expression expressionValueWithObject:nil context:nil];
NSLog(#"%#", result);
NSExpression is very powerful, I suggest you read up on it. You can use variables by passing in objects through the format string.
Change this line
NSString *new=[[NSString alloc]initWithString:#"9+4"];
to
NSString *new=[NSString stringWithFormat:#"%f",9+4];
You will have to manually parse it. You could write a subclass of NSString that overrides the intValue method, and parses it to find arithmetic symbols and perform the math, but thats as close to automatic as you're gonna get I'm afraid
You will need to parse and evaluate it yourself, as seemingly simple calculations like this are beyond the scope of the basic string parsing Apple provides you. It might seem to be a no-brainer if you're used to interpreted languages like Ruby, Perl and the like. But for a compiled language support for runtime evaluation of expressions are uncommon (there are languages that do support them, but Objective-C is not one of them).
When attempting to parse an expression in a string you will want to use Reverse Polish Notation. Here is the first example I cam across in a google search for Objective-C.