how should nsdecimalnumber's be stored in the database?

最后都变了- 提交于 2020-01-04 11:43:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!