Vetuka
Vetuka

Reputation: 1651

How to convert string to currency without rounding up?

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"

Upvotes: 0

Views: 995

Answers (2)

schmidt9
schmidt9

Reputation: 4528

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

Upvotes: 1

PoolHallJunkie
PoolHallJunkie

Reputation: 1363

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)

Upvotes: 1

Related Questions