下面是我以前如何将一个浮点数截断到小数点后两位
NSLog(@" %.02f %.02f %.02f", r, g, b);
我查了文档和电子书,但还没找到答案。谢谢!
下面是我以前如何将一个浮点数截断到小数点后两位
NSLog(@" %.02f %.02f %.02f", r, g, b);
我查了文档和电子书,但还没找到答案。谢谢!
当前回答
为什么要把它弄得这么复杂?你可以用这个代替:
import UIKit
let PI = 3.14159265359
round( PI ) // 3.0 rounded to the nearest decimal
round( PI * 100 ) / 100 //3.14 rounded to the nearest hundredth
round( PI * 1000 ) / 1000 // 3.142 rounded to the nearest thousandth
看它在游乐场工作。
PS:解决方案来自:http://rrike.sh/xcode/rounding-various-decimal-places-swift/
其他回答
你仍然可以在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
以下代码:
import Foundation // required for String(format: _, _)
print(String(format: "a float number: %.2f", 1.0321))
将输出:
a float number: 1.03
延伸的力量
extension Double {
var asNumber:String {
if self >= 0 {
var formatter = NSNumberFormatter()
formatter.numberStyle = .NoStyle
formatter.percentSymbol = ""
formatter.maximumFractionDigits = 1
return "\(formatter.stringFromNumber(self)!)"
}
return ""
}
}
let velocity:Float = 12.32982342034
println("The velocity is \(velocity.toNumber)")
输出: 速度是12.3
@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
或者任何你需要的…
iOS 15+版本推荐:
2.31234.formatted(.number.precision(.fractionLength(1)))