下面是我以前如何将一个浮点数截断到小数点后两位

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/

其他回答

@infix func ^(left:Double, right: Int) -> NSNumber {
    let nf = NSNumberFormatter()
    nf.maximumSignificantDigits = Int(right)
    return  nf.numberFromString(nf.stringFromNumber(left))
}


let r = 0.52264
let g = 0.22643
let b = 0.94837

println("this is a color: \(r^3) \(g^3) \(b^3)")

// this is a color: 0.523 0.226 0.948

为什么要把它弄得这么复杂?你可以用这个代替:

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/

Vincent Guerci的ruby / python %操作符,为Swift 2.1更新:

func %(format:String, args:[CVarArgType]) -> String {
  return String(format:format, arguments:args)
}

"Hello %@, This is pi : %.2f" % ["World", M_PI]

这是一种非常快速和简单的方法,不需要复杂的解决方案。

let duration = String(format: "%.01f", 3.32323242)
// result = 3.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

或者任何你需要的…