0

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

Flarosa
  • 1,287
  • 1
  • 13
  • 27

1 Answers1

0

NSNumberFormatter has a currency style:

import UIKit
import PlaygroundSupport

let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .currency

let number1 = Decimal(25.0)
print(numberFormatter.string(for: number1))

let number2 = Decimal(25.4575)
print(numberFormatter.string(for: number2))
Scott Thompson
  • 22,629
  • 4
  • 32
  • 34
  • Good answer (voted.) Note that you can use the function `string(from:)` (defined in the parent `Formatter` class) and avoid having to convert the value to an NSNumber. – Duncan C Oct 25 '21 at 22:13
  • Also, given that the OP specifically asked to convert a Decimal value to a String, you should probably have used a `Decimal` type in your answer, e.g. `let number1 = Decimal(string: "25.00")` and `print(numberFormatter.string(for: number1)!)` – Duncan C Oct 25 '21 at 22:14
  • OK. I updated the sample. – Scott Thompson Oct 25 '21 at 22:19