In MySQL, we can format a number as a percentage by concatenating the number with the percent sign.
The CONCAT()
function concatenates its arguments. We can pass the number as the first argument, and the percent sign as the second.
Example
Here’s an example to demonstrate:
SELECT CONCAT(3.75, '%');
Result:
3.75%
The function returns a string. 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.0375 * 100, '%');
Result:
3.7500%
We can also format the numeric part with the FORMAT()
function:
SELECT CONCAT(FORMAT(0.0375 * 100, 2), '%');
Result:
3.75%
Here are some more examples with various numbers and format strings:
SELECT
CONCAT(FORMAT(3754, 0), '%') AS "1",
CONCAT(FORMAT(0.0375, 3), '%') AS "2",
CONCAT(FORMAT(3.75, 5), '%') AS "3",
CONCAT(FORMAT(0.0375, 2), '%') AS "4";
Result:
+--------+--------+----------+-------+ | 1 | 2 | 3 | 4 | +--------+--------+----------+-------+ | 3,754% | 0.038% | 3.75000% | 0.04% | +--------+--------+----------+-------+
Add Leading Zeros
We can use LPAD()
to add some leading zeros:
SELECT CONCAT(LPAD(3.45, 5, 0), '%');
Result:
03.45%