私はSwiftプログラミングの初心者で、Xcode 8.2で簡単なチップ計算アプリを作成してきましたIBAction
。計算は以下で設定します。しかし、実際にアプリを実行して、計算する量(23.45など)を入力すると、小数点以下2桁以上になります。.currency
この場合、どのようにフォーマットしますか?
@IBAction func calculateButtonTapped(_ sender: Any) {
var tipPercentage: Double {
if tipAmountSegmentedControl.selectedSegmentIndex == 0 {
return 0.05
} else if tipAmountSegmentedControl.selectedSegmentIndex == 1 {
return 0.10
} else {
return 0.2
}
}
let billAmount: Double? = Double(userInputTextField.text!)
if let billAmount = billAmount {
let tipAmount = billAmount * tipPercentage
let totalBillAmount = billAmount + tipAmount
tipAmountLabel.text = "Tip Amount: $\(tipAmount)"
totalBillAmountLabel.text = "Total Bill Amount: $\(totalBillAmount)"
}
}
通貨を$にする場合は、この文字列初期化子を使用できます。
String(format: "Tip Amount: $%.02f", tipAmount)
デバイスのロケール設定に完全に依存させる場合は、を使用する必要がありNumberFormatter
ます。これは、通貨の小数点以下の桁数を考慮し、通貨記号を正しく配置します。たとえば、double値2.4は、es_ESロケールの場合は「2,40€」、jp_JPロケールの場合は「¥2」を返します。
let formatter = NumberFormatter()
formatter.locale = Locale.current // Change this to another locale if you want to force a specific locale, otherwise this is redundant as the current locale is the default already
formatter.numberStyle = .currency
if let formattedTipAmount = formatter.string(from: tipAmount as NSNumber) {
tipAmountLabel.text = "Tip Amount: \(formattedTipAmount)"
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加