How to format a Double into Currency - Swift 3
You can use this string initializer if you want to force the currency to $:
String(format: "Tip Amount: $%.02f", tipAmount)
If you want it to be fully dependent on the locale settings of the device, you should use a NumberFormatter
. This will take into account the number of decimal places for the currency as well as positioning the currency symbol correctly. E.g. the double value 2.4 will return "2,40 €" for the es_ES locale and "¥ 2" for the jp_JP locale.
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)"
}
Formatting a negative Double into currency in Swift
Use NumberFormatter
:
import Foundation
extension Double {
var formattedAsLocalCurrency: String {
let currencyFormatter = NumberFormatter()
currencyFormatter.usesGroupingSeparator = true
currencyFormatter.numberStyle = .currency
currencyFormatter.locale = Locale.current
return currencyFormatter.string(from: NSNumber(value: self))!
}
}
print(0.01.formattedAsLocalCurrency) // => $0.01
print(0.12.formattedAsLocalCurrency) // => $0.12
print(1.23.formattedAsLocalCurrency) // => $1.23
print(12.34.formattedAsLocalCurrency) // => $12.34
print(123.45.formattedAsLocalCurrency) // => $123.45
print(1234.56.formattedAsLocalCurrency) // => $1,234.56
print((-1234.56).formattedAsLocalCurrency) // => -$1,234.56
Converting String to Currency Swift
You don't need to replace any any characters using regex. Just use NSNumberFormatter
extension String {
// formatting text for currency textField
func currencyFormatting() -> String {
if let value = Double(self) {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.maximumFractionDigits = 2
formatter.minimumFractionDigits = 2
if let str = formatter.string(for: value) {
return str
}
}
return ""
}
}
"74154.7".currencyFormatting() // $74,154.70
"74719.4048014544".currencyFormatting() // $74,719.40
How to get the Currency formatter with decimal and grouping separator in swift using ISOCode
The error comes from the way you cast your value to Int:
Int(1234567.89)
This rounds your floating-point value to 1234567
even before passing it to setAmountString
.
Try casting it to Float
instead, or not casting it at all. You also need to change your function signature from
func setAmountString (amountValue: Int, isoCodeStr: String)
to
func setAmountString (amountValue: Float, isoCodeStr: String)
Rounding a double to 2 decimal places in Swift, XCode 12
You could do it directly inside Text
with the help of string interpolation:
struct ContentView: View {
let decimalNumber = 12.939010
var body: some View {
Text("\(decimalNumber, specifier: "%.2f")")//displays 12.94
}
}
Swift convert Currency string to double
NumberFormatter
can convert to and from string. Also Double
cannot represent certain numbers exactly since it's based 2. Using Decimal
is slower but safer.
let str = "$4,102.33"
let formatter = NumberFormatter()
formatter.numberStyle = .currency
if let number = formatter.number(from: str) {
let amount = number.decimalValue
print(amount)
}
Related Topics
Xcode 8 - Ib Designables - Failed to Render and Update Auto Layout Status, the Agent Crashed
Xcode Quits Unexpectedly Every Time I Open My Project
How to Delete Wkwebview Cookies
How to Detect the Touch Event of an Uiimageview
How to Get Audio Volume Level, and Volume Changed Notifications on iOS
Using Iskindofclass with Swift
How to Change Color of Single Word in Uitextview and Uitextfield
Retrieve Custom Prototype Cell Height from Storyboard
Swift 2: Call Can Throw, But It Is Not Marked with 'Try' and the Error Is Not Handled
Tabbaritems and Setting Their Image Sizes
How to Rotate Text for Uibutton and Uilabel in Swift
Capturing and Storing a Picture Taken with the Camera into a Local Database/Phonegap/Cordova/Ios
Uidatepicker Select Month and Year
How to Apply Uiappearance Proxy Properties to Uilabel