gpt4 book ai didi

Ruby 专家 : can you help/suggest with improving this line of ruby code?

转载 作者:太空宇宙 更新时间:2023-11-03 17:13:25 25 4
gpt4 key购买 nike

拆分制表符分隔的文件后,我在字符串变量中获得了所需的值。不幸的是,这个文件的来源不在我的控制范围内。

以下是该值可能包含的三个确切示例:

  1. “5.344”
  2. “-2.345”
  3. “-.977”

注意空白,小数点前没有“0”,字符串中有双引号。一旦我在我的字段变量中有了每一个,这就是我目前正在做的事情:

int_val = BigDecimal(value_as_string.gsub(/-\./,"-0.").gsub(/\"/,'').strip).round(0).to_i

我需要将每个四舍五入到最接近的整数(.to_i 向下舍入)。任何更好的想法将不胜感激,因为我可以提供帮助,但这很糟糕!?

最佳答案

def round(s)
s.to_f.round
end

round("5.344") # 5
round("-2.345") # -2
round("-.977") # -1

关于Ruby 专家 : can you help/suggest with improving this line of ruby code?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/921640/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com