Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim a trailing .0

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

As you can see, it can be many different datatypes: Float, Int, and String. I am using roo gem to read the file. The problem is that roo interprets integer cells as Float, adding a trailing zero to them (16431 => 16431.0). I want to trim this trailing zero. I cannot use to_i because it will trim all the trailing numbers of the cells that require a decimal in them (the first row in the above example) and will cut everything after a string char in the String rows (the last row in the above example).

Currently, I have a a method that checks the last two characters of the cell and trims them if they are ".0"

def trim(row)
    if row[0].to_s[-2..-1] == ".0"
        row[0] = row[0].to_s[0..-3]
    end
end

This works, but it feels terrible and hacky. What is the proper way of getting my Excel file contents into a Ruby data structure?

like image 655
Dan Garman Avatar asked Aug 30 '13 12:08

Dan Garman


People also ask

How do you trim trailing zeros?

If you want to remove same number of trailing zeros from numbers, you can apply a formula to solve it. Select a adjacent cell to the number you use, type this formula =LEFT(D1,LEN(D1)-3)*1, D1 is the cell you will remove trailing zeros from, 3 is the number or zeros you want to remove.

How do you remove .0 from a string in Python?

Use str.Call str. strip(chars) on a string with "0" as chars to remove zeros from the beginning and end of the string.

How do you get rid of trailing zeros after a decimal?

Multiply by 1. A better way to remove trailing zeros is to multiply by 1 . This method will remove trailing zeros from the decimal part of the number, accounting for non-zero digits after the decimal point. The only downside is that the result is a numeric value, so it has to be converted back to a string.


1 Answers

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
like image 114
sawa Avatar answered Sep 27 '22 17:09

sawa