开发者

How to round Decimal values in Objective C

开发者 https://www.devze.com 2023-01-07 06:21 出处:网络
This may be a easy question but i am not able to find the logic. I am getting the values like this 12.010000

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 m开发者_如何学Pythone out please

Thank You


Try this :

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


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


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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消