How to round decimal values ​​in Objective-C

This may be a simple question, but I cannot find the logic.

I get values ​​like this

12.010000 12.526000 12.000000 12.500000

If I get the value 12.010000, I should display 12.01

If I get the value 12.526000, I need to display 12.526

If I get the value 12.000000, I need to display 12

If I get a value of 12.500000, I should display 12.5

Can someone help me please

thanks

+4
source share
3 answers

Try the following:

  [NSString stringWithFormat: @ "% g", 12.010000]
 [NSString stringWithFormat: @ "% g", 12.526000]
 [NSString stringWithFormat: @ "% g", 12.000000]
 [NSString stringWithFormat: @ "% g", 12.500000]
+4
source
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 might 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]; 

Link: request fooobar.com/questions/77850 / ...

+3
source

Obviously, the taskinoor solution is the best, but you mentioned that you cannot find the logic to solve it ... so here is the logic. You basically scroll the characters in reverse order, looking for either a nonzero or a period character, and then create a substring based on where you find any 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
source

Source: https://habr.com/ru/post/1315615/


All Articles