在数据库中存储 nsdecimalnumbers 的最佳方法是什么? float、real 和 double 等数字类型已被淘汰,因为保持货币使用的精度非常重要。
我考虑过的两种选择是字符串和存储两个整数,一个保存尾数,一个保存指数。后一种方法面临的挑战是,我没有看到一种简单的方法可以从 nsdecimalnumber 中提取尾数和指数。我可以从 NSDecimalNumber 获取 NSDecimal,但尾数和指数属性似乎是私有的!也许我可以反转 number = (尾数 * 10^指数),但是有更好的方法吗?
我的要求是我需要对数据库中的该字段执行一些聚合和操作。如果我存储为字符串,也许执行此计算会更加困难。我仍然需要编写一个自定义函数来对数据库中的尾数和指数求和,所以也许它仍然很重。
编辑:我可以访问指数,但尾数以一种奇怪的方式保存......在调试器中查看它会发现它是一个短(整数)数组。
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 符合 NSCoding,因此您可以使用
encodeWithCoder:
在将其添加到数据库之前,然后使用initWithCoder:
从数据库检索时。请参阅 存档和序列化编程指南,特别是“编码和解码对象”了解有关使用编码器的更多详细信息。
NSDecimalNumber conforms to NSCoding, so you could encode it with
encodeWithCoder:
before adding it to your database, and then decode it usinginitWithCoder:
when retrieving it from the database.See the Archives and Serializations Programming Guide, specifically "Encoding and Decoding Objects" for more details on using encoders.