开发者

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 
                    substringWithR开发者_运维问答ange: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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜