294 floating-point formatting objective-c
我有值25.00的float,但是当我打印在屏幕上它25.0000000.
如何只用两位小数显示值?
And*_*ant 645
这不是数字如何存储的问题,而是您如何显示它的问题.将其转换为字符串时,必须舍入到所需的精度,在您的情况下是两位小数.
例如:
NSString* formattedNumber = [NSString stringWithFormat:@"%.02f", myFloat];
Run Code Online (Sandbox Code Playgroud)
%.02f告诉格式化程序你将格式化一个float(%f),并且应该舍入到两个地方,并且应该用0s 填充.
例如:
%f = 25.000000
%.f = 25
%.02f = 25.00
Run Code Online (Sandbox Code Playgroud)
Vai*_*ran 195
以下是一些更正 -
//for 3145.559706
Run Code Online (Sandbox Code Playgroud)
斯威夫特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"
Run Code Online (Sandbox Code Playgroud)
OBJ-C
@"%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"
Run Code Online (Sandbox Code Playgroud)
等等...
Ric*_*ick 20
您也可以尝试使用NSNumberFormatter:
NSNumberFormatter* nf = [[[NSNumberFormatter alloc] init] autorelease];
nf.positiveFormat = @"0.##";
NSString* s = [nf stringFromNumber: [NSNumber numberWithFloat: myFloat]];
Run Code Online (Sandbox Code Playgroud)
你可能还需要设置负面格式,但我认为它很聪明,可以搞清楚.
cod*_*thm 10
我根据上述答案迅速进行了扩展
extension Float {
func round(decimalPlace:Int)->Float{
let format = NSString(format: "%%.%if", decimalPlace)
let string = NSString(format: format, self)
return Float(atof(string.UTF8String))
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
let floatOne:Float = 3.1415926
let floatTwo:Float = 3.1425934
print(floatOne.round(2) == floatTwo.round(2))
// should be true
Run Code Online (Sandbox Code Playgroud)
在Swift语言中,如果你想表明你需要以这种方式使用它.要在UITextView中指定double值,例如:
let result = 23.954893
resultTextView.text = NSString(format:"%.2f", result)
Run Code Online (Sandbox Code Playgroud)
如果你想在LOG中显示像objective-c那样使用NSLog(),那么在Swift语言中你可以这样做:
println(NSString(format:"%.2f", result))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
263883 次 |
| 最近记录: |