2019-08-13a few seconds read (About 78 words)How to format currency in SwiftIssue #355 123456789101112final class CurrencyFormatter { func format(amount: UInt64, decimalCount: Int) -> String { let formatter = NumberFormatter() formatter.minimumFractionDigits = 0 formatter.maximumFractionDigits = decimalCount formatter.numberStyle = .decimal let value = Double(amount) / pow(Double(10), Double(decimalCount)) let fallback = String(format: "%.0f", value) return formatter.string(from: NSNumber(value: value)) ?? fallback }} 12345678910111213class CurrencyFormatterTests: XCTestCase { func testFormat() { let formatter = CurrencyFormatter() // 120 USD XCTAssertEqual(formatter.format(amount: 120, decimalCount: 0), "120") // 12000 cents XCTAssertEqual(formatter.format(amount: 12000, decimalCount: 2), "120") // 12520 cents XCTAssertEqual(formatter.format(amount: 12520, decimalCount: 2), "125.2") }}#swift