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

swiftserver side programmingprogramming更新于 2025/8/30 12:52:17

有时需要以自定义格式格式化字符串以便在应用程序中使用它们。例如,您可以格式化产品价格、小数点数字等。

在 Swift 中,您可以使用精度说明符来指定小数位数或字符串中显示的字符数。

示例 1

要指定浮点数的小数位数,可以使用 %.nf 格式说明符,其中 n 是小数位数。

import Foundation
let productPrice = 300.3456789
let formattedPrice = String(format: "%.2f", productPrice)
print("格式化的价格为:", formattedPrice)

输出

格式化的价格为: 300.35

"%f"格式是一个字符串,但在上面的例子中,"%.2f"表示小数点后有两位的浮点数。

示例 2

您也可以使用 * 字符作为精度说明符的通配符,在这种情况下,精度将从参数列表中获取。

import Foundation
let productPrice = 300.3456789
let precision = 3
let formattedPrice = String(format: "%.*f", precision, productPrice)
print("格式化的价格为:", formattedPrice)

输出

格式化的价格为: 300.346

使用 rounded() 函数

rounded() 方法将指定值四舍五入为最接近的 int 或 long 值并返回。

Rounded() 方法的语法为

num.rounded()

示例

在此示例中,我们将使用 rounded 函数并将值打印为最接近的 int 或 long 值。

import Foundation
let x = 16.40
print(x.rounded(.toNearestOrAwayFromZero))
// 打印 "16.0"
print(x.rounded(.towardZero))
// 打印"16.0"
print(x.rounded(.up))
// 打印 "17.0"
print(x.rounded(.down))
// 打印 "16.0"

输出

16.0
16.0
17.0
16.0

结论

Swift 格式说明符对于转换值和处理小数非常有用。您可以根据需要以任何方式格式化双精度值和浮点值。



相关文章



关于我们 | 隐私条款 | 学习路线
返回顶部