Answers:
这与数字的存储方式无关,而与显示方式有关。将其转换为字符串时,必须四舍五入到所需的精度,在您的情况下为两位小数。
例如:
NSString* formattedNumber = [NSString stringWithFormat:@"%.02f", myFloat];
%.02f
告诉格式化程序,您将格式化float(%f
),并且应将其四舍五入到两个位置,并用0
s 填充。
例如:
%f = 25.000000
%.f = 25
%.02f = 25.00
25
.. @"%.f"
的伎俩。上面写的不是。
@"%.*f", decimalPlaces, number
%03.f = 025
以下是一些更正-
//for 3145.559706
迅捷3
let num: CGFloat = 3145.559706
print(String(format: "%f", num)) = 3145.559706
print(String(format: "%.f", num)) = 3145
print(String(format: "%.1f", num)) = 3145.6
print(String(format: "%.2f", num)) = 3145.56
print(String(format: "%.02f", num)) = 3145.56 // which is equal to @"%.2f"
print(String(format: "%.3f", num)) = 3145.560
print(String(format: "%.03f", num)) = 3145.560 // which is equal to @"%.3f"
对象
@"%f" = 3145.559706
@"%.f" = 3146
@"%.1f" = 3145.6
@"%.2f" = 3145.56
@"%.02f" = 3145.56 // which is equal to @"%.2f"
@"%.3f" = 3145.560
@"%.03f" = 3145.560 // which is equal to @"%.3f"
等等...
您也可以尝试使用NSNumberFormatter:
NSNumberFormatter* nf = [[[NSNumberFormatter alloc] init] autorelease];
nf.positiveFormat = @"0.##";
NSString* s = [nf stringFromNumber: [NSNumber numberWithFloat: myFloat]];
您可能还需要设置否定格式,但我认为它很聪明可以弄清楚。
根据上述答案,我进行了快速扩展
extension Float {
func round(decimalPlace:Int)->Float{
let format = NSString(format: "%%.%if", decimalPlace)
let string = NSString(format: format, self)
return Float(atof(string.UTF8String))
}
}
用法:
let floatOne:Float = 3.1415926
let floatTwo:Float = 3.1425934
print(floatOne.round(2) == floatTwo.round(2))
// should be true
以下是一些根据精度动态格式化的方法:
+ (NSNumber *)numberFromString:(NSString *)string
{
if (string.length) {
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
f.numberStyle = NSNumberFormatterDecimalStyle;
return [f numberFromString:string];
} else {
return nil;
}
}
+ (NSString *)stringByFormattingString:(NSString *)string toPrecision:(NSInteger)precision
{
NSNumber *numberValue = [self numberFromString:string];
if (numberValue) {
NSString *formatString = [NSString stringWithFormat:@"%%.%ldf", (long)precision];
return [NSString stringWithFormat:formatString, numberValue.floatValue];
} else {
/* return original string */
return string;
}
}
例如
[TSPAppDelegate stringByFormattingString:@"2.346324" toPrecision:4];
=> 2.3453
[TSPAppDelegate stringByFormattingString:@"2.346324" toPrecision:0];
=> 2
[TSPAppDelegate stringByFormattingString:@"2.346324" toPrecision:2];
=> 2.35(向上舍入)