下面是我以前如何将一个浮点数截断到小数点后两位
NSLog(@" %.02f %.02f %.02f", r, g, b);
我查了文档和电子书,但还没找到答案。谢谢!
下面是我以前如何将一个浮点数截断到小数点后两位
NSLog(@" %.02f %.02f %.02f", r, g, b);
我查了文档和电子书,但还没找到答案。谢谢!
当前回答
这里有一个“纯粹的”快速解决方案
var d = 1.234567
operator infix ~> {}
@infix func ~> (left: Double, right: Int) -> String {
if right == 0 {
return "\(Int(left))"
}
var k = 1.0
for i in 1..right+1 {
k = 10.0 * k
}
let n = Double(Int(left*k)) / Double(k)
return "\(n)"
}
println("\(d~>2)")
println("\(d~>1)")
println("\(d~>0)")
其他回答
import Foundation
extension CGFloat {
var string1: String {
return String(format: "%.1f", self)
}
var string2: String {
return String(format: "%.2f", self)
}
}
使用
let offset = CGPoint(1.23, 4.56)
print("offset: \(offset.x.string1) x \(offset.y.string1)")
// offset: 1.2 x 4.6
你仍然可以在Swift中使用NSLog,就像在Objective-C中一样,只是没有@符号。
NSLog("%.02f %.02f %.02f", r, g, b)
编辑:在与Swift合作一段时间后,我想添加这个变化
var r=1.2
var g=1.3
var b=1.4
NSLog("\(r) \(g) \(b)")
输出:
2014-12-07 21:00:42.128 MyApp[1626:60b] 1.2 1.3 1.4
extension Double {
func formatWithDecimalPlaces(decimalPlaces: Int) -> Double {
let formattedString = NSString(format: "%.\(decimalPlaces)f", self) as String
return Double(formattedString)!
}
}
1.3333.formatWithDecimalPlaces(2)
@Christian Dietrich):
而不是:
var k = 1.0
for i in 1...right+1 {
k = 10.0 * k
}
let n = Double(Int(left*k)) / Double(k)
return "\(n)"
也可以是:
let k = pow(10.0, Double(right))
let n = Double(Int(left*k)) / k
return "\(n)"
(更正:) 抱歉混淆* -当然这适用于双打。我认为,最实用的(如果你想让数字四舍五入,而不是被切断)应该是这样的:
infix operator ~> {}
func ~> (left: Double, right: Int) -> Double {
if right <= 0 {
return round(left)
}
let k = pow(10.0, Double(right))
return round(left*k) / k
}
仅对于Float,只需将Double替换为Float, pow替换为powf, round替换为roundf。 更新:我发现它是最实用的使用返回类型Double而不是字符串。它的工作原理与字符串输出相同,即:
println("Pi is roughly \(3.1415926 ~> 3)")
印花:圆周率大约是3.142 所以你可以用同样的方式使用它的字符串(你甚至可以写:println(d ~> 2)),但另外你也可以用它直接舍入值,即:
d = Double(slider.value) ~> 2
或者任何你需要的…
//It will more help, by specify how much decimal Point you want.
let decimalPoint = 2
let floatAmount = 1.10001
let amountValue = String(format: "%0.*f", decimalPoint, floatAmount)