Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decimal places problem with SQLite

Tags:

sqlite

I have a SQLite3 table with a column having format DECIMAL(7,2), but whenever I select rows with values not having a non-zero 2nd decimal place (eg. 3.00 or 3.10), the result always has trailing zero(s) missing (eg. 3 or 3.1). Is there any way that I can apply a formatting function in the SELECT statement so that I get the required 2dp? I have tried ROUND(), but this has no effect. Otherwise I have to keep converting the resulting column values into the required format for display (using Python in my case) every time I do a SELECT statement, which is a real pain.

I don't even mind if the result is string instead of numeric, as long as it has the right number of decimal places.

Any help would be appreciated.

Alan

like image 822
Alan Harris-Reid Avatar asked Oct 02 '10 15:10

Alan Harris-Reid


People also ask

Does SQLite support decimal?

In particular, SQLite doesn't support decimals, so it will convert them to the same floating NUMERIC type it supports.

How do you fix decimal places?

On the Home tab, click Increase Decimal or Decrease Decimal to show more or fewer digits after the decimal point.

How do I allow decimals in SQL?

In standard SQL, the syntax DECIMAL( M ) is equivalent to DECIMAL( M ,0) . Similarly, the syntax DECIMAL is equivalent to DECIMAL( M ,0) , where the implementation is permitted to decide the value of M . MySQL supports both of these variant forms of DECIMAL syntax. The default value of M is 10.

How do I reduce the number of decimal places in SQL?

There are various methods to remove decimal values in SQL: Using ROUND() function: This function in SQL Server is used to round off a specified number to a specified decimal places. Using FLOOR() function: It returns the largest integer value that is less than or equal to a number.


1 Answers

SQLite internally uses IEEE binary floating point arithmetic, which truly does not lend itself well to maintaining a particular number of decimals. To get that type of decimal handling would require one of:

  1. Fixed point math, or
  2. IEEE decimal floating point (rather uncommon), or
  3. Handling everything as strings.

Formatting the values (converting from floating point to string) after extraction is the simplest way to implement things. You could even hide that inside some sort of wrapper so that the rest of the code doesn't have to deal with the consequences. But if you're going to do arithmetic on the value afterwards then you're better off not formatting and instead working with the value as returned by the query, because the format and reconvert back to binary floating point (which Python uses, just like the vast majority of other modern languages) loses lots of information in the reduced precision.

like image 126
Donal Fellows Avatar answered Dec 03 '22 21:12

Donal Fellows