0

How can I get a value from my array, then display it to 2 decimal places?

For example :

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

I get the value 28.34567, but i need two digits after decimal point.

Thanx in advance!

Parsing code:

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

}

And 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 Answers 2

1

A somewhat more powerful way to do this is by using NSNumberFormatter. This allows you a lot more flexibility in determining how you want the number presented, at the expense of complexity:

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];

Update 1: What you have is a localization problem. The floatValue function choked on your number, 29,3508, because your decimal point is not correct (The formatter is expecting 29.3508, instead of 29,3508, which is common in France etc.). That's why the floatValue function will chop off anything after 29, causing your problem.

To fix this, instead of using floatValue to convert your number, use a numberformatter to parse the raw string, before passing it to the formatter.

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];
Sign up to request clarification or add additional context in comments.

2 Comments

Also, can you also post the code you use to parse the number (and XML)? Are you sure you're getting the number as a float/double, instead of a integer?
Hurrah! It works =) Thank you very much, with your help solved the problem.
0

Try this:

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

2 Comments

@foggie: Are you sure you are storing as a float in that Value with content 28.34567 instead of 28?
@KennyTM: objects in the array are added so below NSDictionary *record = [NSDictionary dictionaryWithObjectsAndKeys: //currentValute,@"Valute", currentNumCode,@"NumCode", currentCharCode,@"CharCode", nominal,@"nominal", currentName,@"Name", currentValue,@"Value", nil]; [articles addObject:record];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.