tags:

views:

49

answers:

3

Hi All,

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

+1  A: 
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

Sadat
Hi Sadat thanks for your answer. I tried this code but When i am passing the float value 12.526000, I'm getting the value 12.57 in the "NSString *numberString", but I have to get 12.526 in string value, same as for 12.010000 i am getting 12.02 but i have to get 12.01.Thank You
kiri
Change in this line: [formatter setMaximumFractionDigits:2];place 3 instead of 2.
Sadat
+1  A: 

Try this :

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

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;
}
regulus6633
Thanks for the answer
kiri