fardin
fardin

Reputation: 1477

How to turn float decimal values into integers in ruby

How can one get the decimal values of a float and turn it into an integer in ruby?

Here is how far I got so far:

number = 12.55
decimal_length = number.to_s.split('.')[1].size #=> 2 
decimal = number.divmod(1)[1].round(decimal_length) #=> 0.55

Here how can I turn decimal into integer (55) in a way that it would work with any number as input?

Upvotes: 0

Views: 4487

Answers (3)

Hare Kumar
Hare Kumar

Reputation: 719

Posting little late but I'm hoping it might be helpful

decimal_length = n.to_s.split(".").last.size # 2
decimal = (n.abs.modulo(1)*10**decimal_length).round # 55

Upvotes: 0

Pramod
Pramod

Reputation: 1416

You can use number.to_i to get the integer. To get the decimal value, you can do number%1

    number.to_i => 12
    number%1    => 0.5500000000000007

Upvotes: 3

Mike S
Mike S

Reputation: 11409

Maybe I'm misunderstanding? But you've got it you're just doing extra work.

number = 12.55
number.to_s.split('.')[1].to_i
#  => 55 

Upvotes: 0

Related Questions