0

I have an issue where I need to have result with different precisions maximum one is up to 18 digits after coma.

Because this operation contains money I decided to use Decimal type. So I have questions.

  • Is Decimal data type suitable to represent values up to 18 digits after coma?

  • Will I have different behavior on older phones such as iPhone 5 with that data type?

  • Are any corner cases when usage of the Decimal and NumberFormatter() with maximumFractionDigits = 18 ? (Wrong rounding .. etc)

This is my case with example usage:

I have price for coin in USD:

let pricePerCoin: Decimal = 950.83

Than I have amount in USD that I will use to buy coins.

let amountInUSD: Decimal = 10000

I use formatter to be able to convert Decimal number to string with respect of the maximumFractionDigits.

let fractionDigits = 18

let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.groupingSeparator = ""
formatter.isLenient = true
formatter.maximumFractionDigits = fractionDigits

Result

let result = formatter.string(for: amountInUSD/pricePerCoin) // 10.517127141550011933
B.S.
  • 21,660
  • 14
  • 87
  • 109
Oleg Gordiichuk
  • 15,240
  • 7
  • 60
  • 100
  • 1
    The exact limitations are documented here: https://developer.apple.com/documentation/foundation/nsdecimalnumber. – Martin R Feb 19 '18 at 13:39
  • Note that you lose precision in `let pricePerCoin: Decimal = 950.83`, compare https://stackoverflow.com/a/42782140/1187415 (and write `let pricePerCoin = Decimal(95083)/Decimal(100)` instead) – Martin R Feb 19 '18 at 13:44
  • @MartinR yeah thx for the link. But is the lose of precision (let pricePerCoin = Decimal(95083)/Decimal(100)) is critical in my case? – Oleg Gordiichuk Feb 19 '18 at 13:55
  • 1
    How can I judge how critical the precision is in your application? – It makes the result change from 10.517127141550011933 to 10.517127141550014198, and that is closer to the number 10.51712714155001419812164109251916746421547490087607669089 from Wolfram Alpha. – Martin R Feb 19 '18 at 14:03
  • @MartinR yes you are right thx for help! – Oleg Gordiichuk Feb 19 '18 at 14:20

0 Answers0