Format Decimal as string in Swift?

I'm trying to figure out the right way to format a Decimal number as a currency value in Swift.

For example, if the Decimal contains the value 25.1 I'd want this to print as "$25.10". If it had the value 25, I'd want "$25.00". If it happened to contain a value like 25.4575, I'd want to round it off and display "$25.46".

There are a confusing amount of functions surrounding Decimals and string formatting. I know I can't just use String(format: "%.2f", value) like I can do with floats and doubles.

There appears to be a new FormatStyle property of Decimal, but I can't use that yet because it requires iOS 15.

Thanks, Frank

You may use a NumberFormatter:

import Foundation

let values = [
    "25.1",
    "25",
    "25.4575",
].map{Decimal(string:$0)!}

let formatter = NumberFormatter()
formatter.maximumFractionDigits = 2
formatter.minimumFractionDigits = 0
formatter.currencyCode = "USD"
formatter.numberStyle = .currency

for value in values {
    let string = formatter.string(for: value) ?? "?"
    print(string)
}

Output:

$25.1
$25
$25.46

If the desired output is for the formatted string to always have two decimal places, I guess you would need

formatter.minimumFractionDigits = 2

Format Decimal as string in Swift?
 
 
Q