rails/ruby 上的 DRY 整数浮点转换器 ruby

DRY integer float converter ruby on rails/ruby

我有 NoDataBase 计算器应用程序。它从视图中获取数字参数,使用一些方法在控制器中进行计算并得到 return 答案。问题是在视图中显示正确答案。我需要显示精确的浮点数或整数。 我做了一些转换,但看起来很难看。 我想知道如何实现 DRY 转换器。

链接:

interest_calculator/index.html.erb

interest_calculator_controller.rb

number_to_number spec tests

persent_from_number spec tests

将浮点数四舍五入为 10 个字符

# If accepted parameter is integer, then it shows in view as 5, when it
# is float, it shows as 5.1  
@first_0   = params[:a_0].to_f % 1 != 0 ? params[:a_0].to_f : params[:a_0].to_i
@second_0  = params[:b_0].to_f % 1 != 0 ? params[:b_0].to_f : params[:b_0].to_i
@first_1   = params[:a_1].to_f % 1 != 0 ? params[:a_1].to_f : params[:a_1].to_i
@second_1  = params[:b_1].to_f % 1 != 0 ? params[:b_1].to_f : params[:b_1].to_i  


integer_decimal_converter(@first_0, @second_0, @first_1, @second_1)

如果您不需要全局变量,您可以这样做:

result = [:a_0, :b_0, :a_1, :b_1].map do |key|
  value = params[key].to_f
  value % 1 == 0 ? value.to_i : value
end

integer_decimal_converter(*result)