Swift Convert Currency String to Double

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)
}

Convert currency textfield to double in swift 5?

Based on the extensions you have shown in your code, this should work to convert your currency string into a Double value:

let doubleValue = Double(yourCurrencyString.digits)

Replace yourCurrencyString with whatever variable you're holding your currency string in.

Swift iOS - Convert currency formatted string to number

Fast trick:

let numString = String(number.characters.filter { "0123456789.".characters.contains($0) })           
let number = Double(numString)

Swift - How to convert String to Double

Swift 4.2+ String to Double

You should use the new type initializers to convert between String and numeric types (Double, Float, Int). It'll return an Optional type (Double?) which will have the correct value or nil if the String was not a number.

Note: The NSString doubleValue property is not recommended because it returns 0 if the value cannot be converted (i.e.: bad user input).

let lessPrecisePI = Float("3.14")

let morePrecisePI = Double("3.1415926536")
let invalidNumber = Float("alphabet") // nil, not a valid number

Unwrap the values to use them using if/let

if let cost = Double(textField.text!) {
print("The user entered a value price of \(cost)")
} else {
print("Not a valid number: \(textField.text!)")
}

You can convert formatted numbers and currency using the NumberFormatter class.

let formatter = NumberFormatter()
formatter.locale = Locale.current // USA: Locale(identifier: "en_US")
formatter.numberStyle = .decimal
let number = formatter.number(from: "9,999.99")

Currency formats

let usLocale = Locale(identifier: "en_US")
let frenchLocale = Locale(identifier: "fr_FR")
let germanLocale = Locale(identifier: "de_DE")
let englishUKLocale = Locale(identifier: "en_GB") // United Kingdom
formatter.numberStyle = .currency

formatter.locale = usLocale
let usCurrency = formatter.number(from: "$9,999.99")

formatter.locale = frenchLocale
let frenchCurrency = formatter.number(from: "9999,99€")
// Note: "9 999,99€" fails with grouping separator
// Note: "9999,99 €" fails with a space before the €

formatter.locale = germanLocale
let germanCurrency = formatter.number(from: "9999,99€")
// Note: "9.999,99€" fails with grouping separator

formatter.locale = englishUKLocale
let englishUKCurrency = formatter.number(from: "£9,999.99")

Read more on my blog post about converting String to Double types (and currency).

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)"
}

How can I convert a currency string to a number ignoring separators?

If your intention is to be lenient on the placements of the grouping
separator (which can be a comma or a period, depending on the locale)
then you could remove the formatters currencyGroupingSeparator
from the input string instead of a hard-coded comma:

var input = "£10,00"
if let sep = currencyFormatter.currencyGroupingSeparator {
input = input.replacingOccurrences(of: sep, with: "")
}

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

iOS Swift - Convert String with $ to Double

You could take a "brute force" approach and remove all non-numerics characters from the string and use the internal type conversions directly.

let numberString     = "135,05 kr"
let decimalSeparator = Locale.current.decimalSeparator ?? "."
let decimalFilter = CharacterSet(charactersIn:"-0123456789" + decimalSeparator)
let number = Float(numberString.components(separatedBy:decimalFilter.inverted)
.joined(separator:""))

This will clean up any non numeric characters from the string. So it will not be affected by inconsistent thousand separators or variations of the currency symbol (e.g. if you're working with multiple currencies). You do have to be consistent on the decimal separators though.

Convert currency formatter to double swift

The price is already double from the line

let price = (bagsPrices + mileCosts) * Double(travelers)

thus no need to convert it to double.
The code below will return a string with a $ symbol

currencyFormatter.string(from: NSNumber(value: price))

To get a double from that string then you need to remove the $ symbol

which you can do using removeFirst()

priceString?.removeFirst()

After that, the string can be converted to Double.
The complete code is:

func calculateAirfare(checkedBags: Int, distance: Int, travelers: Int) {


let bagsPrices = Double(checkedBags * 25)
let mileCosts = Double(distance) * 0.10
let price = (bagsPrices + mileCosts) * Double(travelers)

/// Format price

let currencyFormatter = NumberFormatter()
currencyFormatter.numberStyle = .currency

var priceString = currencyFormatter.string(for: price)
priceString?.removeFirst()
print(priceString!)

if let double = Double(priceString!) {
print(double)
}
}


Related Topics



Leave a reply



Submit