kiri
kiri

Reputation: 2007

How to round Decimal values in Objective C

This may be a easy question but i am not able to find the logic.

I am getting the values like this

12.010000 12.526000 12.000000 12.500000

If i get the value 12.010000 I have to display 12.01

If i get the value 12.526000 I have to display 12.526

If i get the value 12.000000 I have to display 12

If i get the value 12.500000 I have to display 12.5

Can any one help me out please

Thank You

Upvotes: 4

Views: 3525

Answers (3)

regulus6633
regulus6633

Reputation: 19030

Obviously taskinoor's solution is the best, but you mentioned you couldn't find the logic to solve it... so here's the logic. You basically loop through the characters in reverse order looking for either a non-zero or period character, and then create a substring based on where you find either character.

-(NSString*)chopEndingZeros:(NSString*)string {
    NSString* chopped = nil;
    NSInteger i;
    for (i=[string length]-1; i>=0; i--) {
        NSString* a = [string substringWithRange:NSMakeRange(i, 1)];
        if ([a isEqualToString:@"."]) {
            chopped = [string substringToIndex:i];
            break;
        } else if (![a isEqualToString:@"0"]) {
            chopped = [string substringToIndex:i+1];
            break;
        }
    }
    return chopped;
}

Upvotes: 0

Sadat
Sadat

Reputation: 3501

float roundedValue = 45.964;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:2];
[formatter setRoundingMode: NSNumberFormatterRoundUp];

NSString *numberString = [formatter stringFromNumber:[NSNumber numberWithFloat:roundedValue]];

NSLog(numberString);
[formatter release];

Some modification you may need-

// You can specify that how many floating digit you want as below 
[formatter setMaximumFractionDigits:4];//2];

// You can also round down by changing this line 
[formatter setRoundingMode: NSNumberFormatterRoundDown];//NSNumberFormatterRoundUp];

Reference: A query on StackOverFlow

Upvotes: 3

taskinoor
taskinoor

Reputation: 46027

Try this :

[NSString stringWithFormat:@"%g", 12.010000]
[NSString stringWithFormat:@"%g", 12.526000]
[NSString stringWithFormat:@"%g", 12.000000]
[NSString stringWithFormat:@"%g", 12.500000]

Upvotes: 4

Related Questions