Julien
Julien

Reputation: 9442

NSNumber to NSString (without trailing zeros if it has decimals)

I'm struggling with this issue, and I couldn't find any resource for it : I have an NSNumber that I want to display in an UITextField, so the user can edit it. So I need to convert this NSNumber to an NSString, like this :

float value  -> desired string value
1.0000000... -> 1
10.000000... -> 10
1.1230000... -> 1.123 or 1,123 depending on the locale
1000000.0... -> 1000000

I've tried to use NSNumberFormatter, but then I get spaces or comas for big numbers :

1000000.0... -> 1,000,000 or 1 000 000 depending on the locale

I also tried

[NSString stringWithFormat:@"%g", val]

But then for big numbers I have a scientific expression :

1000000.0 -> 1e+06

Did somebody have a successful experience with this ?

Upvotes: 1

Views: 870

Answers (3)

AliSoftware
AliSoftware

Reputation: 32681

NSNumberFormatter is the solution, you were on the right path.

But:

  • the formatting it uses depends on the locale (either it uses the default locale if you don't override it, or you can set the locale used by the NSFormatter), because the NSLocale information also carries the Region Formatting info (formatting numbers using the US locale or the FR locale leads to different formats and different representations)
  • You can customize the formatting by tuning the options of NSNumberFormatter, like changing the grouping separators used, changing the decimal separator, etc.

This way you can really customize the way the NSNumberFormatter represents the numeric value into a string.

Upvotes: 3

Saurabh Passolia
Saurabh Passolia

Reputation: 8109

try converting nsnumber value to NSInteger or CGFloat and store it in the new variables. Then set the converted variables to uitextfield.

CGFloat floatNumber = [numberInNSNumber floatValue];

textfield.text = [NSString stringWithFormat:@"%0.2f",floatNumber];

I think it should work for you..!!

Upvotes: -2

Nekto
Nekto

Reputation: 17877

NSNumberFormatter has such method as :

- (void)setGroupingSeparator:(NSString *)string

I think, you can return to variant where you has:

1000000.0... -> 1,000,000 or 1 000 000 depending on the locale

and set additional parameter using that function:

[formatter setGroupingSeparator:@""];

Or moreover try this method:

[formatter setUsesGroupingSeparator:NO];

Upvotes: 3

Related Questions