Gopal Gopal - 6 months ago 26
Ruby Question

Removing trailings zeros in string

I have a string and I need to remove trailing zeros after

.
and possibly the
.
itself:

remove_zeros("1,2,3,4.2300") #=> "1,2,3,4.23"
remove_zeros("1,2,3,4.20300") #=> "1,2,3,4.203"
remove_zeros("1,2,3,4.0200") #=> "1,2,3,4.02"
remove_zeros("1,2,3,4.0000") #=> "1,2,3,4"


How could I do this in Ruby? I tried with converting into
Float
but it terminates the string when I encounter a
,
. Can I write any regular expression for this?

Answer

First, you need to parse the string into its component numbers, then remove the trailing zeros on each number. This can be done by:

1) splitting the string on ',' to get an array of numeric strings

2) for each numeric string, convert it to a Float, then back to a string:

#!/usr/bin/env ruby

def parse_and_trim(string)
  number_strings = string.split(',')
  number_strings.map { |s| Float(s).to_s }.join(',')
end

p parse_and_trim('1,2,3,4.2300') # => "1.0,2.0,3.0,4.23"

If you really want to remove the trailing '.0' fragments, you could replace the script with this one:

#!/usr/bin/env ruby

def parse_and_trim_2(string)
  original_strings = string.split(',')
  converted_strings = original_strings.map { |s| Float(s).to_s }
  trimmed_strings = converted_strings.map do |s|
    s.end_with?('.0') ? s[0..-3] : s
  end
  trimmed_strings.join(',')
end

p parse_and_trim_2('1,2,3,4.2300') # => "1,2,3,4.23"

These could of course be made more concise, but I've used intermediate variables to clarify what's going on.