Skip to content

Integer Coercion bug #107

shingara opened this Issue Jul 26, 2012 · 2 comments

4 participants


I found a little bug with the Coercion in Integer from a string

All is in this gits :

equire 'rspec'
require 'virtus'

class MyObject
  include Virtus
  attribute :int, Integer
  attribute :float, Float

o =
  :int => "334490140000101135",
  :float => "334490140000101135"

describe "Coercion" do                                                                                                                                                                                                                                                          
  it 'should have good conversion in int' do == 334490140000101135
  it 'should have good conversion in float' do
    o.float.should == 334490140000101135.0

# $ rspec virtus_coercion_bug.rb                                                                                                                                                                                                                                       [11:59:47
# F.

# Failures:

#   1) Coercion should have good conversion in int
#      Failure/Error: == 334490140000101135
#        expected: 334490140000101135
#             got: 334490140000101120 (using ==)
#      # ./virtus_coercion_bug.rb:17:in `block (2 levels) in <top (required)>'

# Finished in 0.00043 seconds
# 2 examples, 1 failure

# Failed examples:
# rspec ./virtus_coercion_bug.rb:16 # Coercion should have good conversion in int

The coercion to_integer on String do a to_f on string before doing the to_i but in ruby we have :

irb(main):001:0> "334490140000101135".to_f.to_i
=> 334490140000101120
irb(main):002:0> "334490140000101135".to_i
=> 334490140000101135
dkubb commented Aug 3, 2012

I think this is caused by transforming the string into a float first (to evaluate any scientific notation included in the number) and then convert to an integer.

While I could probably write something to parse scientific notation and then evaluate it in-ruby, I think maybe we should just remove that as a requirement, and just look for positive and negative integers and floats, and that's it.


@solnic, @dkubb :
I fixed it: #111
Please review and merge, if you think my solution is OK.

@solnic solnic closed this in 74db5b4 Sep 1, 2012
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.