2

I'm using Ruby on Rails 4.2.3. If I store a number that has five decimal places in a database field that only allows two decimal places, is the number truncated or automagically rounded?

Does 10.12565 become 10.12 or 10.13?

The database field types for both are decimal data types.

tadman
  • 208,517
  • 23
  • 234
  • 262
mack
  • 2,715
  • 8
  • 40
  • 68
  • 7
    It depends on your database. Isn't it easier just to check it yourself? – Alexey Shein Oct 07 '15 at 16:31
  • 2
    Ruby does nothing in that case. Your database does the thing. – Damien MATHIEU Oct 07 '15 at 16:32
  • 1
    Possible duplicate of [Float vs Decimal in ActiveRecord](http://stackoverflow.com/questions/8514167/float-vs-decimal-in-activerecord) – Brad Werth Oct 07 '15 at 16:34
  • What database are you using? – Alexey Shein Oct 07 '15 at 16:37
  • Postgres is the database – mack Oct 07 '15 at 16:41
  • I didn't realize it was the database that handles this. It looks like Postgres rounds.Sorry for the trivial question. :) – mack Oct 07 '15 at 16:53
  • 1
    Based on a very simple script it looks like postgres will round when the value scale exceeds the column scale – engineersmnky Oct 07 '15 at 16:53
  • 1
    Are you sure it is rounding not truncating? Have you checked the PostgreSQL documentation to see what behavior is specified? Don't trust empirical evidence unless you're willing to check all boundary conditions and special cases and even then things can change during an upgrade unless the behavior is specified. – mu is too short Oct 07 '15 at 17:06
  • If you're really concerned about this, why not write unit tests to verify you're getting the correct behaviour? There's a dozen ways to round numbers, each with various benefits and drawbacks, so ensuring you're using the correct one is a simple process, but a necessary one. – tadman Oct 07 '15 at 17:23

1 Answers1

1

Based on the documentation: http://www.postgresql.org/docs/9.0/static/datatype-numeric.html

In section: 8.1.2. Arbitrary Precision Numbers

They will automatically round:

If the scale of a value to be stored is greater than the declared scale of the column, the system will round the value to the specified number of fractional digits. Then, if the number of digits to the left of the decimal point exceeds the declared precision minus the declared scale, an error is raised.

I would suggest setting your database to the expected result for that field using: http://www.postgresql.org/docs/8.1/static/functions-math.html

Then writing unit tests to ensure you are getting the intended results.

mayo
  • 3,845
  • 1
  • 32
  • 42
mccartjm
  • 121
  • 1
  • 5