Here are two ways to format a number as a percentage in SQLite.
Option 1: The PRINTF()
or FORMAT()
Function
We can use the PRINTF()
or FORMAT()
function to append the percent sign to a number:
SELECT PRINTF('%2d%%', 17);
Result:
17%
When using this function, the percent sign has a special meaning in the format string (it indicates that a substitution follows). If we want the actual percent sign to be included in the output, we need to use two percent signs in the format string.
Here are some more examples:
SELECT
PRINTF('%02d%%', 3.45) AS "1",
PRINTF('%2.2f%%', 3) AS "2",
PRINTF('%1.2f%%', 3.456) AS "3",
PRINTF('%2.3f%%', 3.456) AS "4";
Result:
1 2 3 4 --- ----- ----- ------ 03% 3.00% 3.46% 3.456%
Update: SQLite 3.38.0 (released 22 Feb 2022) renamed the PRINTF()
function to FORMAT()
. The original PRINTF()
name is retained as an alias for backwards compatibility.
Therefore, the first example above can be changed to this:
SELECT FORMAT('%2d%%', 17);
Result:
17%
Option 2: Concatenate
Another way to do it is to use the concatenation operator (||
) to concatenate the number with the percentage sign:
SELECT 3.45 || '%';
Result:
3.45%
The can also work with expressions like this:
SELECT (0.045 * 100) || '%';
Result:
4.5%