Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails ruby四舍五入到小数点后两位并保留零_Ruby On Rails_Ruby_Rounding - Fatal编程技术网

Ruby on rails ruby四舍五入到小数点后两位并保留零

Ruby on rails ruby四舍五入到小数点后两位并保留零,ruby-on-rails,ruby,rounding,Ruby On Rails,Ruby,Rounding,我想用ruby把一个数字四舍五入到小数点后两位 (0.02*270187)。第(2)轮为5403.74,这是正确的 但是 (0.02*278290)。第二轮为5565.8,与前一轮不一致 我想让它看起来像5565.80 请告诉我如何在ruby中实现它 include ActionView::Helpers::NumberHelper number_with_precision(value, :precision => 2) # value.to_f if you have string

我想用ruby把一个数字四舍五入到小数点后两位

(0.02*270187)。第(2)轮为5403.74,这是正确的

但是

(0.02*278290)。第二轮为5565.8,与前一轮不一致

我想让它看起来像5565.80


请告诉我如何在ruby中实现它

include ActionView::Helpers::NumberHelper

number_with_precision(value, :precision => 2) # value.to_f if you have string
还是像这样

'%.2f' % your_value
希望有帮助!
此外,您可以从

中阅读以下内容:

> sprintf("%.2f",(0.02 * 270187))
#=> "5403.74" 
> sprintf("%.2f",(0.02 * 278290))
#=> "5565.80"
> sprintf("%.2f",(0.02 * 270187)).to_f > 100  # If you plan to Compare something with result
#=> true 

> '%.2f' % (0.02 * 270187)
#=> "5403.74"
> '%.2f' % (0.02 * 278290)
#=> "5565.80" 

注意:结果始终是一个字符串,但由于您正在舍入,我假定您这样做是出于演示目的可以按您喜欢的方式格式化任何数字。如果您计划将任何内容与此结果进行比较,则通过在末尾添加
。\u f
将此字符串转换为float

我收到ArgumentError(字符串与0的比较失败)。。。我在Railsy中使用此方法。您可以将字符串转换为类似于
值的浮点值。若要将某个值转换为0,请思考这就是我出现错误的原因。请提供您实际使用的代码。成本=数字精度((到mb(每月使用量)*每mb成本)。若要到f,精度=>2)我收到此错误ArgumentError(将字符串与0进行比较失败):@user4965201:正如我已经说过的,它将作为字符串返回。你试着把一些东西和这个结果进行比较further@user4965201:如果要比较,请在末尾添加
。\u f
。我做过这个cost=('%.2f%](to_mb(每月使用量)*cost_per_mb))。to_f但我得到了一个像5565.8这样的记录,末尾没有零
每月使用量的值是多少
每mb的成本
以及
to_mb(每月使用量)