从NSMutableArray转换对象

时间:2011-03-02 05:44:40

标签: objective-c nsmutablearray

如何从数组中获取值,然后将其显示为2位小数?

例如:

usd.text = [[articles objectAtIndex:9]objectForKey:@"Value"];

我得到值28.34567,但我需要小数点后两位数。

提前Thanx!

解析代码:

-(void)parser:(NSXMLParser *)parser validationErrorOccurred:(NSError *)err 
{
UIAlertView *myAlert = [[UIAlertView alloc]initWithTitle:@"Validation Error" message:err.localizedDescription delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[myAlert show];
[myAlert release];
}

-(void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)err
{
UIAlertView *myAlert = [[UIAlertView alloc]initWithTitle:@"Fatal Error" message:err.localizedDescription delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[myAlert show];
[myAlert release];
}

-(void)parserDidStartDocument:(NSXMLParser *)parser
{

[articles removeAllObjects];
}

-(void)parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict
{
currentElement = elementName;
if ([elementName isEqualToString:@"Valute"]) {
    itemActive = YES;
    currentValute = [[NSMutableString alloc]init];
    currentNumCode = [[NSMutableString alloc]init];
    currentCharCode = [[NSMutableString alloc]init];
    nominal = [[NSMutableString alloc]init];
    currentName = [[NSMutableString alloc]init];
    currentValue = [[NSMutableString alloc]init];
}
}

-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if (itemActive) {
    NSString *fixedString = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

    if ([currentElement isEqualToString:@"NumCode"]) 
        [currentNumCode appendString:fixedString];
    if ([currentElement isEqualToString:@"CharCode"]) 
        [currentCharCode appendString:fixedString];
    if ([currentElement isEqualToString:@"Nominal"]) 
        [nominal appendString:fixedString];
    if ([currentElement isEqualToString:@"Name"])
        [currentName appendString:fixedString];
    if ([currentElement isEqualToString:@"Value"])
        [currentValue appendString:fixedString];


    }

}

-(void)parser:(NSXMLParser *)parser
didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString:@"Valute"]) {
    NSDictionary *record = [NSDictionary dictionaryWithObjectsAndKeys:
                            //currentValute,@"Valute",
                            currentNumCode,@"NumCode",
                            currentCharCode,@"CharCode",
                            nominal,@"nominal",
                            currentName,@"Name",
                            currentValue,@"Value",
                            nil];
    [articles addObject:record];
    [currentNumCode release];
    [currentCharCode release];
    [nominal release];
    [currentName release];
    [currentValue release];
    itemActive = NO;
}
}

-(void)parserDidEndDocument:(NSXMLParser *)parser
{
NSNumberFormatter *oFmt = [[[NSNumberFormatter alloc]init]autorelease];
[oFmt setNumberStyle:NSNumberFormatterDecimalStyle];
[oFmt setMaximumFractionDigits:2];
[oFmt setMinimumFractionDigits:2];
NSNumber *oNum = [NSNumber numberWithDouble:[[[articles objectAtIndex:9]objectForKey:@"Value"]floatValue]];



text.text = [oFmt stringFromNumber:oNum];

}


- (void)viewDidLoad {
[super viewDidLoad];
articles = [[NSMutableArray alloc]init];
NSString *myURL = [NSString stringWithFormat:@"http://www.cbr.ru/scripts/XML_daily.asp"];
NSData  *myData = [NSData dataWithContentsOfURL:[NSURL URLWithString:myURL]];
NSString *myStr = [[NSString alloc]initWithData:myData encoding:NSWindowsCP1251StringEncoding];
myStr = [myStr stringByReplacingOccurrencesOfString:@"encoding=\"windows-1251\"" withString:@""];
NSData *aData = [myStr dataUsingEncoding:NSUTF8StringEncoding];
parser = [[NSXMLParser alloc]initWithData:aData];
parser.delegate = self;
[parser parse];

}

和XML:

<?xml version="1.0" encoding="windows-1251" ?>
<ValCurs Date="01.03.2011" name="Foreign Currency Market">
<Valute ID="R01010">
<NumCode>036</NumCode>
<CharCode>AUD</CharCode>
<Nominal>1</Nominal>
<Name>Австралийский доллар</Name>
<Value>29,3508</Value>
</Valute>
<Valute ID="R01020A">
<NumCode>944</NumCode>
<CharCode>AZN</CharCode>
<Nominal>1</Nominal>
<Name>Азербайджанский манат</Name>
<Value>36,3374</Value>

2 个答案:

答案 0 :(得分:1)

更强大的方法是使用NSNumberFormatter。这样可以更灵活地确定您想要的数字,但代价是复杂性:

NSNumberFormatter *oFmt = [[[NSNumberFormatter alloc] init] autorelease];
[oFmt setNumberStyle:NSNumberFormatterDecimalStyle];
[oFmt setMaximumFractionDigits:2];
[oFmt setMinimumFractionDigits:2]; //Fix to 2 places

NSNumber *oNum = [NSNumber numberWithDouble:[[[articles objectAtIndex:9] objectForKey:@"Value"] doubleValue]];
usd.text = [oFmt stringFromNumber:oNum];

更新1: 你有什么是本地化问题。 floatValue函数在您的数字29,3508上被阻塞,因为您的小数点不正确(格式化程序期望29.3508,而不是29,3508,这在法国很常见等)。这就是为什么floatValue函数会在29之后切掉任何东西,导致你的问题。

要解决此问题,请使用数字格式器解析原始字符串,而不是使用floatValue转换数字,而不是将其传递给格式化程序。

NSNumberFormatter *oParser = [[[NSNumberFormatter alloc] init] autorelease];
[oParser setNumberStyle:NSNumberFormatterDecimalStyle];
[oParser setLocale:oRussianLocale]; //Put in appropriate locale

NSNumber *oParsedNumber = [oParser numberFromString:@"29,3508"]; //replace with your variable

...

[oFmt stringFromNumber:oParsedNumber];

答案 1 :(得分:0)

试试这个:

float v = [[[articles objectAtIndex:9] objectForKey:@"Value"] floatValue];
usd.text = [NSString stringWithFormat:@"%.2f", v];