Storing Currency

We have a need to store currency in Realm (and sync to MongoDB) so what’s the best data type for that?

We will also need be able to perform basic calculations (add, subtract, multiple, divide) and 3 digit precision is fine e.g. 12.345

There are a number of solutions, each with it’s own issues - storing as cents, storing as a string so then we ended up with Decimal128 but that has math issues e.g. this Swift example

let a: Decimal128 = 99.95
let b: Decimal128 = 99.95
let c = a - b
print(c)

and c = 0E-2 when it should be 0 (when printed to console or used as a string)

Any best practices or other solutions?

Does Float give you the precision you need?

If using Decimal128 then 0E-2 == 0, but if you want it to print as 0.0 then you can cast is as a Float - print(Float(c))

1 Like

Thanks @Andrew_Morgan

Floats may possibly work. I think the cast from a Decimal128 to a Float will need to be this

let x = Float( c.doubleValue )

unless you have another suggestion.

Or maybe just

let x = c.doubleValue