本文翻译自:Make a float only show two decimal places
I have the value 25.00
in a float
, but when I print it on screen it is 25.0000000
. 我在float
有25.00
的值,但是当我在屏幕上打印时它是25.0000000
。
How can I display the value with only two decimal places? 如何只用两位小数显示值?
#1楼
参考:https://stackoom.com/question/2Lob/使浮点只显示两位小数
#2楼
If you need to float value as well: 如果您还需要浮动值:
NSString* formattedNumber = [NSString stringWithFormat:@"%.02f", myFloat];
float floatTwoDecimalDigits = atof([formattedNumber UTF8String]);
#3楼
Here's some methods to format dynamically according to a precision: 这里有一些根据精度动态格式化的方法:
+ (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;
}
}
eg 例如
[TSPAppDelegate stringByFormattingString:@"2.346324" toPrecision:4];
=> 2.3453 => 2.3453
[TSPAppDelegate stringByFormattingString:@"2.346324" toPrecision:0];
=> 2 => 2
[TSPAppDelegate stringByFormattingString:@"2.346324" toPrecision:2];
=> 2.35 (round up) => 2.35(向上)
#4楼
lblMeter.text=[NSString stringWithFormat:@"%.02f",[[dic objectForKey:@"distance"] floatValue]];
#5楼
In Swift Language, if you want to show you need to use it in this way. 在Swift语言中,如果你想表明你需要以这种方式使用它。 To assign double value in UITextView, for example: 要在UITextView中指定double值,例如:
let result = 23.954893
resultTextView.text = NSString(format:"%.2f", result)
If you want to show in LOG like as objective-c does using NSLog(), then in Swift Language you can do this way: 如果你想在LOG中显示像objective-c那样使用NSLog(),那么在Swift语言中你可以这样做:
println(NSString(format:"%.2f", result))
#6楼
I made a swift extension based on above answers 我根据上述答案迅速进行了扩展
extension Float {
func round(decimalPlace:Int)->Float{
let format = NSString(format: "%%.%if", decimalPlace)
let string = NSString(format: format, self)
return Float(atof(string.UTF8String))
}
}
usage: 用法:
let floatOne:Float = 3.1415926
let floatTwo:Float = 3.1425934
print(floatOne.round(2) == floatTwo.round(2))
// should be true