Working with currencies. How to simplify this conversion of String to Decimal?

187 Views Asked by At

I am working with currencies in Swift. I need to convert a String to Decimal. There are few problems which I think I have solved:

  • decimal type uses ".", but some locales use ","
  • users may type additional extra digits by mistake (hence "2500,12345" in my example code)
  • not all currencies have 2 fraction digits, some have 0 or 3

But the question is:

How to simplify this code?

As you can see in code, I am moving back and forth between String and NSDecimal to solve the problems mentioned above. And I am thinking that there is probably an easier way. I was hoping I could tell Swift to cut unnecessary fractions during first conversion from String to Decimal. Using currencyFormatter.maximumFractionDigits somehow. But when I print the value of currencyFormatter.maximumFractionDigits it has the correct value (2 in case of USD) only after currencyFormatter.numberStyle = .currency

Any ideas? :)

import Foundation

let amountString = "2500,12345"
var amountDecimal: Decimal = 0
var finalDecimal: Decimal = 0
print("amountString (\(type(of: amountString))):", amountString)

let currencyFormatter = NumberFormatter()
// Set locale to Polish, where decimal separator is "," instead of "."
currencyFormatter.locale = Locale(identifier: "pl_PL")
currencyFormatter.numberStyle = .decimal

// Convert String to Decimal and change , to .
if let number = currencyFormatter.number(from: amountString) {
    amountDecimal = number.decimalValue
    print("amountDecimal (\(type(of: amountDecimal))):", amountDecimal)
}

// set currency to USD
currencyFormatter.numberStyle = .currency
currencyFormatter.currencyCode = "USD"

let amountCurrency = currencyFormatter.string(for: amountDecimal)
print("amountCurrency (\(type(of: amountCurrency))):", amountCurrency ?? "0")

if let number = currencyFormatter.number(from: amountCurrency ?? "0") {
    finalDecimal = number.decimalValue
    print("finalDecimal (\(type(of: finalDecimal))):", finalDecimal)
}

EDIT: So far this is for iOS app where users will provide Strings using TextField with keyboard set to numerical with decimals.

0

There are 0 best solutions below