DarkLeafyGreen
DarkLeafyGreen

Reputation: 70406

How to format this NSString correctly?

I want to format a string that can look like that:

0.0580 which means 5.8 ct

0.1580 which means 15.8 ct

1.1580 which means 1.15 €

So the string can be anything in x.xxxx format. Now I started formating it but I am new to objective-c and iOS.

First I want to remove the last character because the last number does not really matter and I don't want to round numbers.

NSString *responseString = [responseData 
                    substringWithRange:NSMakeRange(1, 
                             [responseData length]-2)];

This gives me x.xxx so far. Any idea how to proceed and what code to use? Are there any libraries on that?

Upvotes: 0

Views: 226

Answers (2)

gstroup
gstroup

Reputation: 1064

Take a look at the NSNumberFormatter class. It should do what you need. Something like this:

NSNumberFormatter *numFormatter = [[NSNumberFormatter alloc] init];
NSNumber *myNumber = [NSNumber numberWithDouble:[@"0.158" doubleValue]]; 
[numFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
NSString *formattedValue = [numFormatter stringFromNumber:myNumber];
[numFormatter release];

Also look at NSNumberFormatterStyle and NSNumberFormatterBehavior to control the format.

Upvotes: 3

FreeAsInBeer
FreeAsInBeer

Reputation: 12979

Once you have your number in the form x.xxx, you could do something like:

float floatValue = [@"0.158" floatValue]; // Get your string as a number.
floatValue *= 100; // Turn '0.158' into '1.58'

Does this answer your question? I'm not quite sure that it does, so update your question and I will try to assist you better.

Upvotes: 1

Related Questions