TomRossi7 wrote in post #970346:
> I have currency information that I plan to store as an integer --
> ironically to avoid issues like this. The user input will always be
> in a decimal form. I'm thinking I will just do this ('291.15'.to_f *
> 100).round instead. That should round out any of the weird float
> issues.
As was said before by others in this thread, using the BigDecimal type
really is the most reliable, and simple, solution. Don't reinvent
the wheel with calculating in pennies and rounding etc. ...
In the migration, do this:
class AddAmountToPayment < ActiveRecord::Migration
def self.up
add_column :payments, :amount, :decimal, :precision => 12, :scale =>
2
end
...
This which will work automatically correct when reading
user input in your forms and when doing internal calculations:
$ rails c
Loading development environment (Rails 3.0.3)
001:0> Payment.columns.select{|c| c.sql_type =~ /decimal/}
=> [#<ActiveRecord::ConnectionAdapters::MysqlColumn:0xb6c1e844
@sql_type="decimal(12,2)", @scale=2, @name="amount", @limit=12,
@precision=12, @primary=false, @type=:decimal, @default=nil,
@null=true>]
002:0> payment = Payment.new(:amount => "291.15")
=> #<Payment id: nil, user_id: nil, testing: nil, created_at: nil,
updated_at: nil, amount: #<BigDecimal:b6c09318,'0.29115E3',8(12)>>
003:0> payment.amount
=> #<BigDecimal:b6c07e14,'0.29115E3',8(12)>
004:0> payment.amount.to_s
=> "291.15"
...
019:0> (payment.amount - BigDecimal("291") - BigDecimal("0.15")).to_s
=> "0.0"
020:0> ((291.15 - 291) - 0.15).to_s
=> "-2.27318164292001e-14" # Rounding errors with float !!!
HTH,
Peter
--
Posted via http://www.ruby-forum.com/.
--
You received this message because you are subscribed to the Google Groups "Ruby
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en.