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


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

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

示例 1

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

import Foundation
let productPrice = 300.3456789
let formattedPrice = String(format: "%.2f", productPrice)
print("The formatted price is: ", formattedPrice)

输出

The formatted price is: 300.35

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

示例 2

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

import Foundation
let productPrice = 300.3456789
let precision = 3
let formattedPrice = String(format: "%.*f", precision, productPrice)
print("The formatted price is: ", formattedPrice)

输出

The formatted price is: 300.346

使用 rounded() 函数

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

rounded() 方法的语法是

num.rounded()

示例

在这个例子中,我们将使用 rounded 函数并将值打印到最接近的 int 或 long 值。

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

输出

16.0
16.0
17.0
16.0

结论

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

更新于:2023年1月3日

浏览量 1K+

启动你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.