Trim a trailing .0

前端 未结 4 1092
我在风中等你
我在风中等你 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条回答
  •  猫巷女王i
    2021-02-19 01:52

    This should cover your needs in most cases: some_value.gsub(/(\.)0+$/, '').

    It trims all trailing zeroes and a decimal point followed only by zeroes. Otherwise, it leaves the string alone.

    It's also very performant, as it is entirely string-based, requiring no floating point or integer conversions, assuming your input value is already a string:

    Loading development environment (Rails 3.2.19)
    irb(main):001:0> '123.0'.gsub(/(\.)0+$/, '')
    => "123"
    irb(main):002:0> '123.000'.gsub(/(\.)0+$/, '')
    => "123"
    irb(main):003:0> '123.560'.gsub(/(\.)0+$/, '')
    => "123.560"
    irb(main):004:0> '123.'.gsub(/(\.)0+$/, '')
    => "123."
    irb(main):005:0> '123'.gsub(/(\.)0+$/, '')
    => "123"
    irb(main):006:0> '100'.gsub(/(\.)0+$/, '')
    => "100"
    irb(main):007:0> '127.0.0.1'.gsub(/(\.)0+$/, '')
    => "127.0.0.1"
    irb(main):008:0> '123xzy45'.gsub(/(\.)0+$/, '')
    => "123xzy45"
    irb(main):009:0> '123xzy45.0'.gsub(/(\.)0+$/, '')
    => "123xzy45"
    irb(main):010:0> 'Bobby McGee'.gsub(/(\.)0+$/, '')
    => "Bobby McGee"
    irb(main):011:0>
    

提交回复
热议问题