BigDecimal/Double precision
(1) By anonymous on 2022-11-28 12:52:45 [link] [source]
I'm trying to use BigDecimal where the value 12.00 should be different than 12.0 or 12, how do i handle it with sqlite?
(2.1) By Keith Medcalf (kmedcalf) on 2022-11-28 14:23:33 edited from 2.0 in reply to 1 [link] [source]
Use text. As numbers (integer or real (floating point)) they are all the same value.
That is, to be precise, 12.00 == 12.0 == 12
The only way for SQLite to think them different is to format them appropriately and store them as text. Then you will find that ' 12.00 '
!= ' 12.0 '
!= ' 12 '
, as long as the comparison is carried out in the text domain.
Note that each text field is formatted with up to 8 digits blank padded on the left forming the "integer part" of the text field, a decimal point ('.') if the number is to be considered a "decimal", followed by 8 digits of decimal part blank padded on the right. Converting the numbers to and fro however you are representing them on your appplication side and the text representation on the SQLite3 side is for you to figure out yourself.
If you do not require SQLite3 to compare the text representations, then you may represent them any way you like (as text) and any comparison or ordering is your problem to solve in your application.
NOTE Added single-ticks to make the text fields preserve blanks.
(3) By Keith Medcalf (kmedcalf) on 2022-11-28 14:31:40 in reply to 2.1 [link] [source]
Note that the binary/text format you choose is your choice. If you are going to require SQLite3 to "compare" or "sort" them you will have to provide either a correct sortable formatting that does what you want, or provide your own "compare" functions. If you expect them to be sortable or comparable, you will need to provide your own collation function (and store the data as text so that collation applies).
(4) By Lifepillar (lifepillar) on 2022-11-28 15:46:24 in reply to 1 [source]
Depending on your requirements, you may better off modeling the value and its formatting separately. For instance, T(Value, NumTrailingZeroes, …). Then, you may easily write queries that compare the values numerically, e.g.:
select * from T where Value = 12; — Matches 12, 12.0, 12.00, …
(or whatever operator is used for BigDecimals) and queries testing for a specific format, e.g.:
select * from T where Value = 12 and NumTrailingZeroes = 2; — Only 12.00
Having a separate attribute will also make it easier to pass the relevant info, say, to printf-style functions.
NumTrailingZeroes is just an example: you may find it more convenient to store the number of significant digits or the number of decimal places instead.