简体   繁体   中英

How to show two digits in float value

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

 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]] ;

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM