0

我正在为一个网站编写报告,我目前正在考虑处理 BigDecimal -0.0 的最佳方法。

我正在使用的数据库有很多。当这些-0.0 通过number_to_currency()时,我得到“$-0.00”。我的负数格式实际上是“-$x.xx”,所以请注意 number_to_currency 没有将其格式化为负数(否则美元符号前也会有一个负号),但由于某种原因,负数符号与 0 一起被翻译。

现在我的解决方案是每次从数据库中获取金额时都这样做:

amount *= -1 if amount == 0 && amount.sign == -1

这会将 -0.0 更改为 0.0。这很简单,但我不禁想知道是否有更好的解决方案,或者 BigDecimals 或 number_to_currency 上的东西来处理我只是找不到的这种情况。

4

1 回答 1

2

之所以如此,是因为数字被转换为要显示的字符串。和:

# to_d converts to BigDecimal, just FYI
"-0".to_d.to_s #=> "-0.0"

因此,您必须自己将其设为 0。但是符号检查是多余的——与 0 的简单比较就可以了:

bdn = "-0".to_d # or BigDecimal.new("-0")
value = bdn.zero? ? 0 : bdn
number_to_currency(value, other_options)

但是,您不希望在调用的任何地方手动添加此检查number_to_currencymodified_number_to_currency在 ApplicationHelper中创建自己的方法会更方便,如下所示:

def modified_number_to_currency( number, options )
  value = number.zero? ? 0 : number
  number_to_currency(value, options)
end

然后使用modified_number_to_currency代替number_to_currency.

或者,您可以覆盖number_to_currency并让它super最终调用。这也可能有效,但我不是 100% 确定。

具体来看您的检查:

amount *= -1 if amount == 0 && amount.sign == -1

它应该是:

amount = 0.to_d if amount.zero? # the to_d might or might not be required
于 2014-12-19T15:53:39.053 回答