问题
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:
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.
来源:https://stackoverflow.com/questions/3919127/how-should-nsdecimalnumbers-be-stored-in-the-database