Swift 中的精确字符串格式说明符 [英] Precision String Format Specifier In Swift

查看:33
本文介绍了Swift 中的精确字符串格式说明符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我之前如何将浮点数截断为两位小数

Below is how I would have previously truncated a float to two decimal places

NSLog(@" %.02f %.02f %.02f", r, g, b);

我查看了文档和电子书,但无法弄清楚.谢谢!

I checked the docs and the eBook but haven't been able to figure it out. Thanks!

推荐答案

迄今为止我最好的解决方案,来自 David 的回应:

My best solution so far, following from 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 的解决方案,将格式化操作直接绑定到数据类型.很可能某处有一个内置的格式化操作库,或者它可能很快就会发布.请注意,该语言仍处于测试阶段.

I think this is the most Swift-like solution, tying the formatting operations directly to the data type. It may well be that there is a built-in library of formatting operations somewhere, or maybe it will be released soon. Keep in mind that the language is still in beta.

这篇关于Swift 中的精确字符串格式说明符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆