Oscady
Oscady

Reputation: 93

Removing any zeros from the end of an integer

I would like to remove any zeros from the end of an integer. For example, if I have 14260, I would like to end up with 1426. 142600 I would also like to end up with 1426.

I have had a look around and can't find a solution for integers, just a lot of people talking about removing leading zeros and zeros from floats.

Upvotes: 3

Views: 2406

Answers (2)

Ilya
Ilya

Reputation: 13487

To additional, you can process it like number:

num = 1220000
num_without_zeros = num

while num_without_zeros % 10 == 0 do
  num_without_zeros /= 10
end

num_without_zeros
#=> 122

Upvotes: 3

shivam
shivam

Reputation: 16506

convert to string, sub and convert back to int:

142600.to_s.sub(/0+$/,'') # /0+$/ is regex to find all trailing 0s
#=> "1426"

14200006000000000.to_s.sub(/0+$/,'').to_i
#=> 14200006

Upvotes: 6

Related Questions