20

The documentation doesn't have examples.

https://www.postgresql.org/docs/10/datatype-numeric.html#DATATYPE-NUMERIC-TABLE

NUMERIC(precision, scale)

I want to use the smallest amount of space to save a positive number that will be at most 100 and I need to accept decimal increments of 0.5

What precision and scale should I use in this case?

2 Answers 2

29

Use numeric(4, 1).

This gives you a total of 4 digits maximum (including the decimal part), with 1 digit reserved for the decimals, so this would store numbers up until 999.9.

If you can live with numbers that are not greater than 99.9, then numeric(3, 1) is fine.

2
  • 1
    Thanks! so precision is # of digits, scale is # of decimal digits.
    – Zach G
    Commented May 22, 2020 at 23:07
  • @ZachG: yes, exactly.
    – GMB
    Commented May 22, 2020 at 23:12
3

NUMERIC(4,1) will do, but this will also accept decimals such as:

55.0
26.3
978.1

This is because precision declares maximum of digits a number can hold and scale relates to decimal part. You would also need to validate your input.

If you wish to do this at database level, you could use CHECK column_name <= 100.0. Such check could also be extended to accept only numbers with .0 and .5 decimal part (see modulo operator).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.