SwiftUI Text で数値をフォーマットする
SwiftUI の Text は数値を直接受け取り、format: 引数で様々なフォーマットを適用できます。NumberFormatter を使わずに、宣言的に数値表示を記述できます。
基本的な数値フォーマット
整数や小数をフォーマットして表示します。
let number = 1234567
Text(number, format: .number) // "1,234,567"小数点以下の桁数を指定:
let value = 3.14159
Text(value, format: .number.precision(.fractionLength(2)))
// "3.14"通貨表示
.currency() で通貨フォーマットを適用します。
let price = 1980.0
Text(price, format: .currency(code: "JPY"))
// "¥1,980"
Text(price, format: .currency(code: "USD"))
// "$1,980.00"パーセント表示
.percent で百分率表示ができます。
let ratio = 0.75
Text(ratio, format: .percent) // "75%"小数点以下も指定可能:
let ratio = 0.7532
Text(ratio, format: .percent.precision(.fractionLength(1)))
// "75.3%"測定単位
Measurement 型と組み合わせて単位付きの値を表示します。
let distance = Measurement(value: 5, unit: UnitLength.kilometers)
Text(distance, format: .measurement(width: .abbreviated))
// "5 km"
let weight = Measurement(value: 72.5, unit: UnitMass.kilograms)
Text(weight, format: .measurement(width: .abbreviated))
// "72.5 kg"バイト数
ByteCountFormatStyle でファイルサイズなどを表示します。
let bytes: Int64 = 1_500_000
Text(bytes, format: .byteCount(style: .file))
// "1.5 MB"リスト表示
配列を自然な文章として表示することもできます。
let fruits = ["りんご", "みかん", "ぶどう"]
Text(fruits, format: .list(type: .and))
// "りんご、みかん、およびぶどう"format 引数のおかげで、複雑な数値フォーマットもシンプルに記述できます。











