基于十进制值在number_to_currency中使用动态精度值 [英] Using a dynamic precision value in number_to_currency based on the decimal value

查看:85
本文介绍了基于十进制值在number_to_currency中使用动态精度值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们的整个应用中,我们使用 number_to_currency(value,:precision => 2)。但是,我们现在有一个要求,该值可能需要显示到三个或更多的小数位,例如

Thoughout our app we use number_to_currency(value, :precision => 2). However, we now have a requirement whereby the value may need displaying to three or more decimal places, e.g.

0.01  => "0.01"
10    => "10.00"
0.005 => "0.005"

在我们当前的实现中,第三个示例表示为:

In our current implementation, the third example renders as:

0.005 => "0.01"

对我来说,最好的方法是什么?能否使 number_to_currency 对我有用?如果不是,我如何确定给定的浮点值应显示到多少小数位? sprintf(%g,value)差不多了,但是我不知道如何使它始终满足最小2dp的要求。

What's the best approach for me to take here? Can number_to_currency be made to work for me? If not, how do I determine how many decimal places a given floating point value should be displayed to? sprintf("%g", value) comes close, but I can't figure out how to make it always honour a minimum of 2dp.

推荐答案

由于精度问题,以下内容不适用于普通浮点数,但是如果您使用的是 BigDecimal 应该可以正常工作。

The following will not work with normal floats, because of precision problems, but if you're using BigDecimal it should work fine.

def variable_precision_currency(num, min_precision)
  prec = (num - num.floor).to_s.length - 2
  prec = min_precision if prec < min_precision
  number_to_currency(num, :precision => prec)
end


ruby-1.8.7-p248 > include ActionView::Helpers

ruby-1.8.7-p248 > puts variable_precision_currency(BigDecimal.new("10"), 2)
$10.00

ruby-1.8.7-p248 > puts variable_precision_currency(BigDecimal.new("0"), 2)
$0.00

ruby-1.8.7-p248 > puts variable_precision_currency(BigDecimal.new("12.45"), 2)
$12.45

ruby-1.8.7-p248 > puts variable_precision_currency(BigDecimal.new("12.045"), 2)
$12.045

ruby-1.8.7-p248 > puts variable_precision_currency(BigDecimal.new("12.0075"), 2)
$12.0075

ruby-1.8.7-p248 > puts variable_precision_currency(BigDecimal.new("-10"), 2)
$-10.00

ruby-1.8.7-p248 > puts variable_precision_currency(BigDecimal.new("-12.00075"), 2)
$-12.00075

这篇关于基于十进制值在number_to_currency中使用动态精度值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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