The root of this problem is three-fold:
- As of Version 5.6, Swift does not support Decimal literals.
- Decimal() supports up to 38 digits of precision.
- Double() supports about 17 digits of precision.
Hence when using Decimals to represent numbers with more than 17 digits of precision, it is crucial to never do anything that would convert the Decimal's value to a Double. This includes initializing with literals:
print (Decimal(1234567890.12345678901234567890))
// 1234567890.1234569216
print (Decimal(string: "1234567890.12345678901234567890")!)
// 1234567890.12345678901234567890
Decimal(1234567890.12345678901234567890)
produces the value 1234567890.1234569216
because 1234567890.12345678901234567890
is a Double literal, limited to about 17 digits of precision.
Sadly, NumberFormatter has evidently never gotten the memo on this problem.
var dec = Decimal(string: "1234567890.12345678901234567890")!
let f = NumberFormatter()
f.numberStyle = .decimal
f.minimumFractionDigits = 20
print (f.string(from: dec as NSDecimalNumber)!) // 1,234,567,890.12346000000000000000
So at the present time, there is no way to make Swift accurately produce localized, decimal numbers with more than about 17 digits of precision. NumberFormatter cannot produce, for example, the String 1,234,567,890.12345678901234567890 even though Decimal can represent that exact value.
You can get non-localized string representations of Decimals using String(describing:)
print (String(describing:(Decimal(string: "1234567890.12345678901234567890")!)))
// 1234567890.1234567890123456789
For one of my own apps I made a little "poor man's" Decimal formatter, which simply outputs the full value using the decimal separator from the desired Locale:
let locale = Locale(identifier: "fr_FR")
dec = Decimal(string: "1234567890,12345678901234567890", locale: locale)!
let formatter = NumberFormatter()
formatter.locale = locale
let localizedSeparator = String(formatter.decimalSeparator.first ?? ".")
let fractionDigits = 20
var strings = String(describing:(dec)).split(separator: (Locale.current.decimalSeparator?.first) ?? "." )
var result = strings[0]
if fractionDigits > 0 {
if strings.count > 1 {
while strings[1].count < fractionDigits { strings[1] += "0" }
result += localizedSeparator + String(strings[1].prefix(fractionDigits))
}
else {
result += localizedSeparator + (0..<fractionDigits).map{_ in "0"}
}
}
print (result) // 1234567890,12345678901234567890
formatter.generatesDecimalNumbers = true
but even that does not work due to a bug inNumberFormatter
, compare https://mcmap.net/q/1078469/-generatesdecimalnumbers-for-numberformatter-does-not-work/1187415 which also has a workaround. – LoritalornNumber
using the binary floating point typeDouble
for its internal representation. And the precision ofDouble
is restricted to approx. 17 decimal digits. – Loritalorn