Tag: 小数

奇怪的舍入问题

使用小数和浮点数发生了一些非常奇怪的事情,我无法理解为什么或在哪里(ruby / rails / postgresql)。 给定带有小数列的购买表 – 总计 : p1 = Purchase.where(total: 5.99).first_or_create p2 = Purchase.where(total: 5.99).first_or_create [p1.id, p2.id] # => [1, 2] p3 = Purchase.where(total: 5.99.to_d).first_or_create p4 = Purchase.where(total: 5.99.to_d).first_or_create [p3.id, p4.id] # => [1, 1] 无论小数或浮点数,Ruby和postgresql都没有完全代表5.99的问题: 5.99.to_s # => “5.99” 5.99.to_d.to_s # => “5.99” 5.99 == 5.99.to_d # => true SELECT CAST(5.99 AS […]

根据十进制值在number_to_currency中使用动态精度值

虽然我们的应用程序使用number_to_currency(value, :precision => 2) 。 但是,我们现在有一个要求,即值可能需要显示三个或更多小数位,例如 0.01 => “0.01” 10 => “10.00” 0.005 => “0.005” 在我们当前的实现中,第三个示例呈现为: 0.005 => “0.01” 我最好的方法是什么? 可以使用number_to_currency为我工作吗? 如果没有,我如何确定给定浮点值应显示多少个小数位? sprintf(“%g”, value)接近,但我无法弄清楚如何使它始终尊重至少2dp。

Rails:无法在迁移中添加:precision或:scale选项和change_column?

这似乎在之前被问过: rails decimal precision和scale 但是当为:precision或:scale运行change_column迁移时,它们实际上不会影响架构或数据库,但db:migrate运行时没有错误。 我的迁移文件如下所示: class ChangePrecisionAndScaleOfPaybackPeriodInTags 3, :precision => 10 } end def self.down change_column :tags, :payback_period, :decimal end end 但我的架构(和数据)仍然如下: t.decimal “payback_period” 别人有这个问题吗? 谢谢, 玩笑

截断浮点数而不进行舍入

我有一个浮点数,我想截断到3个位置,但我不想舍入。 例如,将1.0155555555555555转换为1.015 (不是1.016 )。 我将如何在Ruby中执行此操作?