简体   繁体   中英

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 (eg 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.

在大多数情况下,我认为小数与浮点数没有什么区别-我怀疑您会发现小数的行为有很大不同。

我很久以前就问过这个问题,但是如果我没记错的话,那只是Rails Beta版中的一个错误,并且在Rails 4的最终版本中表现出预期。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM