views:

31

answers:

1

What is the best way to store nsdecimalnumbers in a database? Numeric types like float, real and double are out, because it is important to preserve the precision for currency usage.

The two alternatives I have considered are string and storing two ints, one holding the mantissa and one holding the exponent. The challenge facing the latter approach is that I dont see an easy way to pull the mantissa and exponent out of the nsdecimalnumber. I can get NSDecimal from NSDecimalNumber, but the mantissa and exponent properties seem to be private! Perhaps I can reverse number = (mantissa * 10^exponent), but is there a better way to do this?

The requirement I have is that I would need to perform some aggregate sum operations on this field in the database. If I store as a string, perhaps performing this calculation would be more difficult. I would still need to write a custom function to sum over a mantissa and exponent in the database, so maybe its still as heavy.

Edit: I can access the exponent, but the mantissa is kept in a weird manner...poking at it in the debugger reveals that it is an array of short(ints).

+1  A: 

NSDecimalNumber conforms to NSCoding, so you could encode it with encodeWithCoder: before adding it to your database, and then decode it using initWithCoder: when retrieving it from the database.

See the Archives and Serializations Programming Guide, specifically "Encoding and Decoding Objects" for more details on using encoders.

Robot K
This is an interesting proposal. What if the database is not only looked at by the iphone, but synced up to a server where it may be poked at with PHP or Java?
Ying
It's not as straightforward, but you could make it work. Probably the best way is to write your own encoder and create the equivalent decoder (or deserializer) classes in Java and PHP. However, now you're back to your original question, as you have to decide how to properly encode the components of NSDecimal.
Robot K