Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to obtain an unformatted string representation of an NSDecimal or NSDecimalNumber?

I have an NSDecimal and need this as technical string, i.e. with no formatting in any way. Floating point should be a "." if there is any, and minus sign should just be a "-" if there is any. besides that, there should be no formatting going on like grouping or chinese numbers.

I was looking for 2 hours through the SDK but it seems there is nothing simple to accomplish this. Are there solutions for this?

like image 574
Another Registered User Avatar asked Nov 29 '09 14:11

Another Registered User


3 Answers

For NSDecimal, you can use NSDecimalString with a specified locale:

NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
NSString *decimalString =  NSDecimalString(&decimalValue, usLocale);
[usLocale release];

The U.S. locale uses a period for the decimal separator, and no thousands separator, so I believe that will get you the kind of formatting you're looking for.

As others have pointed out, for an NSDecimalNumber you can use the -descriptionWithLocale: method with the above-specified U.S. locale. This doesn't lose you any precision.

like image 100
Brad Larson Avatar answered Oct 26 '22 11:10

Brad Larson


NSDecimalNumber

NSLog(@"%@", [theNumber stringValue]);

NSDecimal

NSLog(@"%@", NSDecimalString(&theDecimal, nil));
like image 22
2 revs Avatar answered Oct 26 '22 12:10

2 revs


NSDecimalNumber is a subclass of NSNumber which has the -stringValue method.

stringValue

Returns the receiver’s value as a human-readable string.

- (NSString *)stringValue

Return Value

The receiver’s value as a human-readable string, created by invoking descriptionWithLocale: where locale is nil.

descriptionWithLocale:

Returns a string that represents the contents of the receiver for a given locale.

- (NSString *)descriptionWithLocale:(id)aLocale

Parameters aLocale

An object containing locale information with which to format the description. Use nil if you don’t want the description formatted.

Just call [theNumber stringValue].

like image 3
Georg Schölly Avatar answered Oct 26 '22 13:10

Georg Schölly