Issue #355
final 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
}
}
class 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")
}
}