在 Ruby 中将美分转换为美元字符串,而不使用 BigDecimal
我想在 Ruby 中正确地将美分转换为美元。我永远不需要用零头的钱来工作。
是否可以在不使用 BigDecimal 的情况下正确执行此操作(没有浮点错误)?
例如,美分换算美元
"99" => "0.99"
"324" => "3.24"
以下似乎可行,但它正确吗?
(cents.to_i/100.0).to_s
更新:我注意到如果 cents
= "10287349283923497624861294712974892742837833"
,上面的行不起作用。
I want to convert from cents to dollars correctly in Ruby. I will never have to work with fractions of cents.
Is it possible to do this correctly (without floating point errors) without having to use BigDecimal
?
E.g., cents to dollars
"99" => "0.99"
"324" => "3.24"
The following seems to work, but is it correct?
(cents.to_i/100.0).to_s
Update: I noticed the line above doesn't work if cents
= "10287349283923497624861294712974892742837833"
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
Micheal Kohl 已经回答了:看看金钱宝石。
例子:
乍一看,没问题,但是:
你没有 2 位数字。
选择:
As Micheal Kohl already answered: Take a look to the money gem.
Example:
On the first look, it is ok, but:
You don't have 2 digits.
Alternative:
您也可以考虑使用有理数。但是,我不确定它们在 sprintf 编辑时是否会转换为浮点数:
You can consider using Rationals as well. However, I am not sure do they get converted to floats when sprintf-ed:
如果它们已经是刺痛,你可以使用字符串操作并完全绕过数字问题:
没有精度问题,没有浮点,没有bignums,没有Rational,没有什么棘手的,没有什么聪明的。需要进行一些简单的修改来处理负值,但这将与已有的一样简单。
If they're stings already you could use string manipulation and bypass the numeric problems completely:
No precision issues, no floating point, no bignums, no Rational, nothing tricky, nothing clever. Some simple modifications would be needed to deal with negative values but that will be as simple as what's already there.
就我个人而言,我不会尝试重新发明这个特定的轮子并使用 金钱宝石。来自文档(添加了重点):
Personally I wouldn't try to re-invent this specific wheel and go with the money gem. From the docs (emphasis added):
这是一种单行方法,也简单地使用字符串操作,从而完全绕过数字问题:
Here's a one-line method that also simply uses string manipulation thereby completely bypassing the numeric issues:
这些答案相当古老,所以我希望下一个人知道有一种更简单的方法(如果您使用的是 Rails)。
有货币和精度选项。请参阅 Rails 文档
These answers are fairly old, so I wanted the next person to know there's an easier way (if you're using Rails).
There's currency and precision options. See Rails documentation
您可以使用
fdiv
来实现此目的。它返回两个数字相除后的浮点结果->
price.to_i.fdiv(100)
例如:
'123'.to_i.fdiv(100) -> 1.23
You can use
fdiv
for this purpose. It returns the floating point result after division of two numbers->
price.to_i.fdiv(100)
For example:
'123'.to_i.fdiv(100) -> 1.23