Below is a quick example of formatting a number as a percentage in MariaDB.
The CONCAT()
function concatenates its arguments. We can therefore pass the number as the first argument, and the percent sign as the second.
Example
Here’s an example to demonstrate:
SELECT CONCAT(7.45, '%');
Result:
7.45%
The result is a string that displays the number as a percentage value. The number is implicitly converted to a string before the percent sign is added.
We can also pass expressions like the following:
SELECT CONCAT(0.0745 * 100, '%');
Result:
7.4500%
We can also format the numeric part with the FORMAT()
function:
SELECT CONCAT(FORMAT(0.0745 * 100, 2), '%');
Result:
7.45%
Here are some more examples with various numbers and format strings:
SELECT
CONCAT(FORMAT(2745, 0), '%') AS "1",
CONCAT(FORMAT(0.0745, 3), '%') AS "2",
CONCAT(FORMAT(2.35, 5), '%') AS "3",
CONCAT(FORMAT(0.0745, 2), '%') AS "4";
Result:
+--------+--------+----------+-------+ | 1 | 2 | 3 | 4 | +--------+--------+----------+-------+ | 2,745% | 0.075% | 2.35000% | 0.07% | +--------+--------+----------+-------+
Add Leading Zeros
We can use LPAD()
to add some leading zeros:
SELECT CONCAT(LPAD(2.75, 5, 0), '%');
Result:
02.75%