如何在浮点值中显示两位数字
How to show two digits in float value
我正在使用此代码在浮点值中的点后显示数字:
NSString *string = [NSString stringWithFormat:@"%.02f", floatValue];
如果像 65.5234 这样的 floatValue 可以工作并且 string = 65.52
但是如果 float 值像 65.5025 它不起作用并且 string=65.5
如何更改?我需要将我的字符串显示为 65.50
我正在与 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]] ;
这适用于代码:
float floatValue = 65.5025;
NSString *string = [NSString stringWithFormat:@"%.02f", floatValue];
NSLog(@"string: %@", string);
输出:
string: 65.50
请提供未产生预期结果的完整示例(如上所示)。
有关详细信息,请参阅 man printf。
我认为你所拥有的是正确的。在 iOS7 上用 xcode 6.1.1
为你做了一个小测试 iPhone
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);
输出:
Test from string1 = 65.50
Test from string2 = 65.503
Test from string3 = 65.5025
那么您的代码似乎还有其他问题?您使用的是最新的 xcode 吗?在你的系统上试试这个例子,看看打印出来的是什么。您的浮动变量是否可以在某处进行调整?
我正在使用此代码在浮点值中的点后显示数字:
NSString *string = [NSString stringWithFormat:@"%.02f", floatValue];
如果像 65.5234 这样的 floatValue 可以工作并且 string = 65.52 但是如果 float 值像 65.5025 它不起作用并且 string=65.5
如何更改?我需要将我的字符串显示为 65.50 我正在与 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]] ;
这适用于代码:
float floatValue = 65.5025;
NSString *string = [NSString stringWithFormat:@"%.02f", floatValue];
NSLog(@"string: %@", string);
输出:
string: 65.50
请提供未产生预期结果的完整示例(如上所示)。
有关详细信息,请参阅 man printf。
我认为你所拥有的是正确的。在 iOS7 上用 xcode 6.1.1
为你做了一个小测试 iPhonefloat 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);
输出:
Test from string1 = 65.50
Test from string2 = 65.503
Test from string3 = 65.5025
那么您的代码似乎还有其他问题?您使用的是最新的 xcode 吗?在你的系统上试试这个例子,看看打印出来的是什么。您的浮动变量是否可以在某处进行调整?