Swift中的精度字符串格式说明符

下面是我以前截断一个浮点到两个小数位
NSLog(@" %.02f %.02f %.02f",r,g,b);

我检查了文档和电子书,但没有能够弄清楚。谢谢!

我最好的解决方案到目前为止,从 David’s response
import Foundation

extension Int {
    func format(f: String) -> String {
        return String(format: "%\(f)d",self)
    }
}

extension Double {
    func format(f: String) -> String {
        return String(format: "%\(f)f",self)
    }
}

let someInt = 4,someIntFormat = "03"
println("The integer number \(someInt) formatted with \"\(someIntFormat)\" looks like \(someInt.format(someIntFormat))")
// The integer number 4 formatted with "03" looks like 004

let someDouble = 3.14159265359,someDoubleFormat = ".3"
println("The floating point number \(someDouble) formatted with \"\(someDoubleFormat)\" looks like \(someDouble.format(someDoubleFormat))")
// The floating point number 3.14159265359 formatted with ".3" looks like 3.142

我认为这是最Swift的解决方案,将格式化操作直接绑定到数据类型。很可能在某处有一个内置的格式化操作库,或者很快就会发布。请注意,该语言仍处于测试阶段。

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...