Search code examples
sqliteformatnumber-formatting

sqlite3 format "12345.6789" to "12,345.68" on the native command line


This works as expected:
select printf("%f", 12345.6789); 12345.678900

This works as expected:
select printf("%.2f", 12345.6789); 12345.68

This works as expected (notice the comma):
select printf("%,d", 12345.6789); 12,345

WHERE is my comma?
select printf("%,.2f", 12345.6789); 12345.68

Trying to get "12345.6789" to output as "12,345.68" without resorting to a Python script. Ideally, I would like to do this on the native sqlite command line.

A Python script would be a cinch but I just want to undestand why the comma works only intemittently.


Using sqlite3 version 3.37.2 on an Ubuntu box. Several days of searching for an answer and I've come up dry. ChatGPT failed me as well!


Solution

  • It works with Sqlite 3.45.1:

    sqlite> select printf('%,.2f', 12345.6789);
    12,345.68
    

    Note the use of single quotes instead of double quotes - single quotes in SQL indicate strings, double quotes are used for identifiers like table and column names. Older versions of SQLite accepted them for strings too but recent versions disable that by default in the command line shell, so your version would generate an error.

    Looking through the changelogs, I found this entry for 3.42.0:

    Extended the built-in printf() function so the comma option now works with floating-point conversions in addition to integer conversions.

    So you're just using too old a version to support that particular combination.