价格字段的字符串,十进制或浮点数据类型? [英] String, decimal, or float datatype for price field?

查看:339
本文介绍了价格字段的字符串,十进制或浮点数据类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个价格字段/列(例如15.50 USD),我不知道Rails数据类型应该是字符串,十进制还是浮动?

I've got a price field/column (eg. 15.50 USD) and I wonder should the Rails datatype be string, decimal, or float?

推荐答案

这个参数总是有两边 - 小数和整数。整数的支持者认为小数可能不准确(当执行转换时),并且BigDecimal实现包括错误,有时甚至是segfault。

This argument always has two sides - decimals and integers. Supporters of integers argue that decimals might not be accurate (when doing conversions) and that the BigDecimal implementation includes bugs, sometimes even segfaulting.

对于我自己的项目,我拾起整数也将它们包装在自定义容器中,将分数转换为真实金额并返回。起初它似乎很好,一段时间后,它变得非常麻烦使用 - 跟踪当你处理美分,当格式化字符串等。

For my own project, i picked up integers also, wrapped them in a custom container, converting cents to "real" amounts and back. At first it seemed nice, after a while it became really cumbersome to use - tracking when you are dealing with cents, when with formatted strings etc.

然后我还原为小数 - 相同的格式,所有的时间,我可以很容易地将金额转换为分,如果需要,我得到不同的舍入算法开箱。

Then i reverted to decimals - same format all the time, i can easily convert the amount to cents if needed, i get the different rounding algorithms out of the box. Im much much more satisfied with decimals.

并且为了解决小数不准确的问题 - 当Google搜索时,您可能会注意到大多数错误与将小数转换为浮动:)
由于vise已经提到过,浮动不准确,你永远不应该将你的十进制转换为浮点数。这是处理小数时你必须记住的唯一最重要的事情 - 你不想失去转换的准确性。
当我使用BigDecimal时,我从来没有遇到ruby 1.8.7,1.8.7和1.9.1的任何错误。

And to address the issues about decimals not being accurate - when googling you might notice that most of the bugs are related to converting decimals into floats :) As vise already mentioned before, floats are not accurate and you should never ever convert your decimal to a float. That's the single most important thing you have to remember when dealing with decimals - you don't want to lose accuracy by conversions. Oh and i have never actually encountered any bugs with ruby 1.8.7, 1.8.7 and 1.9.1 while using BigDecimal extensively.

这篇关于价格字段的字符串,十进制或浮点数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆