title: Working with currencies. How to simplify this conversion of String to Decimal?
body: <p>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:</p>
  <ul>
  <li>decimal type uses &quot;.&quot;, but some locales use &quot;,&quot;</li>
  <li>users may type additional extra digits by mistake (hence &quot;2500,12345&quot; in my example code)</li>
  <li>not all currencies have 2 fraction digits, some have 0 or 3</li>
  </ul>
  <p>But the question is:</p>
  <p><strong>How to simplify this code?</strong></p>
  <p>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 <strong>currencyFormatter.maximumFractionDigits</strong> somehow. But when I print the value of <strong>currencyFormatter.maximumFractionDigits</strong> it has the correct value (2 in case of USD) only after <strong>currencyFormatter.numberStyle = .currency</strong></p>
  <p>Any ideas? :)</p>
  <pre><code>import Foundation
  
  let amountString = &quot;2500,12345&quot;
  var amountDecimal: Decimal = 0
  var finalDecimal: Decimal = 0
  print(&quot;amountString (\(type(of: amountString))):&quot;, amountString)
  
  let currencyFormatter = NumberFormatter()
  // Set locale to Polish, where decimal separator is &quot;,&quot; instead of &quot;.&quot;
  currencyFormatter.locale = Locale(identifier: &quot;pl_PL&quot;)
  currencyFormatter.numberStyle = .decimal
  
  // Convert String to Decimal and change , to .
  if let number = currencyFormatter.number(from: amountString) {
      amountDecimal = number.decimalValue
      print(&quot;amountDecimal (\(type(of: amountDecimal))):&quot;, amountDecimal)
  }
  
  // set currency to USD
  currencyFormatter.numberStyle = .currency
  currencyFormatter.currencyCode = &quot;USD&quot;
  
  let amountCurrency = currencyFormatter.string(for: amountDecimal)
  print(&quot;amountCurrency (\(type(of: amountCurrency))):&quot;, amountCurrency ?? &quot;0&quot;)
  
  if let number = currencyFormatter.number(from: amountCurrency ?? &quot;0&quot;) {
      finalDecimal = number.decimalValue
      print(&quot;finalDecimal (\(type(of: finalDecimal))):&quot;, finalDecimal)
  }
  </code></pre>
  <p>EDIT:
  So far this is for iOS app where users will provide Strings using TextField with keyboard set to numerical with decimals.</p>