I have a problem similar to the one in this question: How to obtain an unformatted string representation of an NSDecimal or NSDecimalNumber? I need to have a number in string format accurately represented as an NSNumber, but this number is converted back to a string in other places, and I can't avoid that. The problem I'm having is that when the number is converted back to a string, the string is in scientific notation in some cases.
NSDecimalNumber *dn = [NSDecimalNumber decimalNumberWithString:@"0.0001"];
NSString *s = [dn stringValue]; // s will be @"1E-4"
How can I prevent this number from being displayed in scientific notation?
I am working in a circa 2005 version of GNUstep (possibly v1.11.1 for GNUstep Base), rather than on mac or iPhone, which may account for some of the differences in behavior vs the other question I referenced. I have looked over the base library API and the documentation in my own GNUstep install, but I can't seem to find anything to help.
EDIT 2/7/12:
The question has changed slightly, but the goal is still the same. Originally, I didn't think I was able to control the string output piece, but I can pass the value back as a string. At this point I am attempting to use a formatting string, but I still want to prevent the scientific notation from appearing.
[NSString stringWithFormat:@"%1.14g", [val doubleValue]]
I've chosen to use %g
because we would like a specific number of significant digits for the value. If I use %f
, I can trim the extra zeros, but the number does not always come out cleanly. 800000000.79 appears as 800000000.7899999600, for example.
Is there a way to get a cleanly formatted number with up to a certain number of significant digits (or decimal places) without displaying scientific notation before that number of digits?
I'm willing to accept C advice as well.
Try printing the number using NSNumberFormatter instead of the stringValue method. It has a lot more options.
(I'm assuming NSNumberFormatter is available on GNUstep)