0

I am using following code to convert string to US currency. However, I could not figure out how to disable round up.

For example, if the string value is "0.000012" code converts it to "$0.00".

The extension I am using it is from this SO answer:

The way I use:

print(Formatter.currency.locale)    // "en_US (current)\n"
print(priceUsdInt.currency)         // "$1.99\n"
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
Vetuka
  • 1,523
  • 1
  • 24
  • 40
  • `0.000012` rounded to 2 digits is `0.00`... so what is your question actually? – holex Oct 24 '17 at 11:58
  • I do not want it to be rounded. I want it to be "$0.00012" – Vetuka Oct 24 '17 at 12:01
  • then please try reading the `NumberFormatter` [docs](https://developer.apple.com/documentation/foundation/numberformatter) first, focusing on the `usesSignificantDigits` and `minimumSignificantDigits` properties, perhaps...? – holex Oct 24 '17 at 12:20
  • I will, thank you holex. – Vetuka Oct 24 '17 at 15:09

2 Answers2

1

0.000012 is should NOT convert to 0.01 , that would be wrong. If you want to set up a different format you can change the decimal points

String(format: "%0.3f", string)
PoolHallJunkie
  • 1,345
  • 14
  • 33
  • Code converts it to "$0.00" not "0.01". I want to apply decimals into the existing code if possible. Thank you for the reply! – Vetuka Oct 24 '17 at 12:05
1

To control rounding (accept 6 digits after point in this case) add formatter.maximumFractionDigits = 6; to your Formatter extension

extension Formatter {
    static let currency = NumberFormatter(style: .currency)
    static let currencyUS: NumberFormatter = {
        let formatter = NumberFormatter(style: .currency)
        formatter.locale = Locale(identifier: "en_US")
        formatter.maximumFractionDigits = 6;
        return formatter
    }()
    static let currencyBR: NumberFormatter = {
        let formatter = NumberFormatter(style: .currency)
        formatter.locale = Locale(identifier: "pt_BR")
        formatter.maximumFractionDigits = 6;
        return formatter
    }()
}
schmidt9
  • 4,436
  • 1
  • 26
  • 32