0

I'm using this code to show digits after dot in float value:

NSString *string = [NSString stringWithFormat:@"%.02f", floatValue];

if may floatValue like 65.5234 it works and string = 65.52 But if float value like 65.5025 it doesn't work and string=65.5

How can I change it? I need to show my string as 65.50 I'm working with iOS 7

Arthur
  • 1,740
  • 3
  • 16
  • 36
  • 5
    `NSNumberFormatter`? – Larme Jan 22 '15 at 13:18
  • 1
    possible duplicate of [Make a float only show two decimal places](http://stackoverflow.com/questions/560517/make-a-float-only-show-two-decimal-places) – Andrei Jan 22 '15 at 13:18
  • I think you should explain better your problem ora at least the expected result it seems a duplicate of http://stackoverflow.com/questions/1343890/rounding-number-to-2-decimal-places-in-c – Andrea Jan 22 '15 at 13:18
  • I found my error. After rounding i'm using NSNumberFormatter to split number for categories 65 256.60. Now i'm rounding and splitting only with NSNumberFormatter – Arthur Jan 22 '15 at 13:30
  • Shouldn't the format specifier simply be `%.2f`? No need for the zero. – rmaddy Jan 22 '15 at 15:43

3 Answers3

2
 NSNumberFormatter *format = [[NSNumberFormatter alloc]init];
[format setNumberStyle:NSNumberFormatterDecimalStyle];
[format setRoundingMode:NSNumberFormatterRoundHalfUp];
[format setMaximumFractionDigits:2];
[format setMinimumFractionDigits:2];

string = [NSString stringWithFormat:@"%@",[format stringFromNumber:[NSNumber numberWithFloat:65.50055]] ;
Fawad Masud
  • 12,219
  • 3
  • 25
  • 34
2

This works with the code:

float floatValue = 65.5025;
NSString *string = [NSString stringWithFormat:@"%.02f", floatValue];
NSLog(@"string: %@", string);

Output:

string: 65.50

Please provide a complete example (like the above) that does not produce the desired result.

See man printf for more information.

zaph
  • 111,848
  • 21
  • 189
  • 228
  • If you intend to show the number in the UI you should take internationalization into consideration. Not all locales use "." as their decimal separator. – David Rönnqvist Jan 22 '15 at 13:32
0

What you have would seem correct to me. Did a small test for you in iOS7 on an iPhone, built with xcode 6.1.1

float val=65.5025;
NSString *string1 = [NSString stringWithFormat:@"%.02f", val];
NSString *string2 = [NSString stringWithFormat:@"%.03f", val];
NSString *string3 = [NSString stringWithFormat:@"%.04f", val];
NSLog(@"Test from string1 = %@",string1);
NSLog(@"Test from string2 = %@",string2);
NSLog(@"Test from string3 = %@",string3);

Output:

Test from string1 = 65.50
Test from string2 = 65.503
Test from string3 = 65.5025

So looks like something else is going on with your code? Are you using the latest xcode. Try this example on your system and see what prints out. Could your float variable be getting adjusted somewhere?

Rory McKinnel
  • 7,936
  • 2
  • 17
  • 28