Inkling
Inkling

Reputation: 3782

Decimal values showing up incorrectly

I'm completely new to rails and have a bit of a question about some decimal values from my database showing up as being slightly off by a very small amount in the default scaffolding index/show outputs in the browser. I have an item where the specific value of an attribute is 9.12, which I can confirm is stored in my sqlite3 database correctly as a decimal. However on the index page, or the show page for the item, it's giving me 9.119999999999999

Just to be even more confusing, if I attempt to edit the item the form will show the precise value of 9.12 in the relevant field.

By playing around a bit I can see that other values (for instance 9.11, 9.13, 9.14, 9.123) will give me similar precision errors in the html output, while many others (e.g. 9.1, 9.09, 9.15, 9.121) will display as they should.

Now I realize that this kind of behaviour is expected when using float values because of the way they're stored in binary, but my understanding was that a decimal shouldn't have any such quirks to do with precision. If that's true then all I can assume is that the issue lies with Rails. So can anyone enlighten me on what causes this behaviour?

Obviously I can update my view so as to make it display properly like so:

<%= number_with_precision(item.value, precision: 2) %>

but considering that each item I seeded in the db has a plethora of decimal values that all display just fine, I don't want to have to do this for every decimal value when the issue seems to be the exception rather than the rule.

I'm using Rails 4.0.0beta1 with Ruby 2.0.0 by the way (in order to follow along with the latest edition of the Agile Web Development with Rails book). I'd be interested to know if the same thing happens in Rails 3.2

Edit: ironically everything shows up correctly if I update the database to use a float type instead.

Upvotes: 1

Views: 280

Answers (2)

Inkling
Inkling

Reputation: 3782

I asked this question a long time ago, but if I remember correctly it was just a bug in the beta version of Rails and behaved as expected in the final version of Rails 4.

Upvotes: 0

Sudhir Jonathan
Sudhir Jonathan

Reputation: 17526

I don't think decimals are treated any differently than floats for most cases - I doubt that you'll find a significant difference in their behaviour.

Upvotes: 0

Related Questions