Trim a trailing .0

前端 未结 4 1066
我在风中等你
我在风中等你 2021-02-19 01:02

I have an Excel column containing part numbers. Here is a sample

\"\"

As you can see, it can be many differ

4条回答
  •  天涯浪人
    2021-02-19 01:49

    def trim num
      i, f = num.to_i, num.to_f
      i == f ? i : f
    end
    
    trim(2.5) # => 2.5
    trim(23) # => 23
    

    or, from string:

    def convert x
      Float(x)
      i, f = x.to_i, x.to_f
      i == f ? i : f
    rescue ArgumentError
      x
    end
    
    convert("fjf") # => "fjf"
    convert("2.5") # => 2.5
    convert("23") # => 23
    convert("2.0") # => 2
    convert("1.00") # => 1
    convert("1.10") # => 1.1
    

提交回复
热议问题