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+

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告