繁体   English   中英

从NSMutableArray转换对象

[英]Convert object from NSMutableArray

如何从数组中获取一个值,然后显示到小数点后两位?

例如 :

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

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

提前感谢!

解析代码:

-(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>

执行此操作的一种更强大的方法是使用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点之后将任何内容截断,从而导致问题的原因。

要解决此问题,请先使用numberformatter解析原始字符串,然后再将其传递给formatter,而不是使用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];

尝试这个:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM