Sergey Petrov
Sergey Petrov

Reputation: 21

How To Cast Float to Integer?

I'm stuck on casting Float to Integer in below function - it never comes to v.to_int (sorry, I'm novice in Ruby and it is a monkey coding). Issue I'm trying to resolve is data that comes from MongoDB supposed to be of Type Integer, but sometimes there are Floats in input stream(see below).

What I'm trying to achieve - when Integer expected on particular position - Cast and Truncate to Integer whatever comes there(usually Float).

def transform_primitive(v, type=nil)
  case v
  when BSON::ObjectId, Symbol
    v.to_s
  when BSON::Binary
    if type.downcase == 'uuid'
      v.data.to_s.unpack("H*").first
    else
      Sequel::SQL::Blob.new(v.data.to_s)
    end
  when Mongo::DBRef
    v.id.to_s
  when Integer
    v.to_int
  else
    v
  end
end

input looks like below, so last value 150.0 expected to be 150

[ "EUR",  20]
[ "EUR",  30]
[ "EUR",  450]
[ "EUR",  22]
[ "EUR",  150.0]

Used Ruby 2.7 MongoDB 3.4 Source Library (MoSQL) is not mine, repo is here

Upvotes: 2

Views: 394

Answers (1)

To match both integers and floats you need to change the when condition to:

when Integer, Float

Or just when Float as the Integer case is covered by the else already.

Observe:

3.is_a? Integer #=> true
3.is_a? Float #=> false
3.4.is_a? Integer #=> false
3.4.is_a? Float #=> true

Alternatively you can use the class Numeric:

when Numeric

Note that Numeric includes not only integers and floats but also complex and rational numbers:

(1+0i).is_a? Numeric

I think this should be ok in your case, but just pointing it out.

Btw, instead of to_int you may want to use round:

3.4.to_i #=> 3
3.6.to_i #=> 3
3.4.round #=> 3
3.6.round #=> 4

Upvotes: 5

Related Questions