下面是我以前如何将一个浮点数截断到小数点后两位
NSLog(@" %.02f %.02f %.02f", r, g, b);
我查了文档和电子书,但还没找到答案。谢谢!
下面是我以前如何将一个浮点数截断到小数点后两位
NSLog(@" %.02f %.02f %.02f", r, g, b);
我查了文档和电子书,但还没找到答案。谢谢!
当前回答
斯威夫特4
let string = String(format: "%.2f", locale: Locale.current, arguments: 15.123)
其他回答
use
CGFloat
or
Float.roundTo(places: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)
您也可以用这种方式创建操作符
operator infix <- {}
func <- (format: String, args:[CVarArg]) -> String {
return String(format: format, arguments: args)
}
let str = "%d %.1f" <- [1453, 1.123]
@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
你还不能用字符串插值来做。你最好的选择仍然是NSString格式化:
println(NSString(format:"%.2f", sqrt(2.0)))
从python中推断,合理的语法可能是:
@infix func % (value:Double, format:String) -> String {
return NSString(format:format, value)
}
然后允许你使用它们作为:
M_PI % "%5.3f" // "3.142"
你可以为所有的数字类型定义类似的操作符,不幸的是我还没有找到一种方法来使用泛型。
Swift 5更新
至少在Swift 5中,String直接支持format: initializer,所以不需要使用NSString, @infix属性也不再需要,这意味着上面的示例应该写成:
println(String(format:"%.2f", sqrt(2.0)))
func %(value:Double, format:String) -> String {
return String(format:format, value)
}
Double.pi % "%5.3f" // "3.142"