SQL TO_CHAR number formatting
TO_CHAR(1234567.891, 'FM999,999,999.00') renders a number as '1,234,567.89'. The mask controls every digit position, which CONVERT styles and FORMAT do not.
- Catégorie
- Conversion
- Returns
text- In this category
- 10 of 39
Syntaxe
TO_CHAR(number, format_mask)
Prise en charge des moteurs
| Moteur | Support | Notes |
|---|---|---|
| SQL Server | Different name or syntax | no TO_CHAR; FORMAT(value, 'N2') or CONVERT with styles |
| PostgreSQL | Oui | Supported under this name. |
| MySQL | Different name or syntax | FORMAT(value, 2) rounds and separates but has no masks |
| SQLite | Different name or syntax | printf('%.2f', v), also spelled format() from 3.38 |
| Oracle | Oui | Supported under this name. |
Exemples
PostgreSQL
SELECT TO_CHAR(1234567.891, 'FM999,999,999.00') AS total;
Oracle
SELECT TO_CHAR(salary, 'L99G999D00') AS pay FROM employees;
PostgreSQL
SELECT TO_CHAR(42, 'FM000099') AS zero_padded;
Bon à savoir
- FM strips the padding TO_CHAR adds to reserve sign space. Without it, TO_CHAR(42, '999') returns ' 42' with a leading blank, the classic why-is-there-a-space mystery.
- 9 is a digit shown if significant, 0 forces a digit (leading zeros), D and G are the locale's decimal point and group separator, L is the local currency symbol. ',' and '.' are always comma and period.
- Digits past the mask's scale are rounded, never truncated: TO_CHAR(0.567, '0.99') is ' 0.57'. With '9.99' the leading zero disappears and you get ' .57'.
- A number too wide for the mask prints as # characters instead of erroring: TO_CHAR(12345, '999') is '####' on Oracle and ' ###' on PostgreSQL. Check masks against the largest value you expect.
Questions about TO_CHAR (numbers)
Why a leading space in my number?
TO_CHAR reserves a character for the sign of negative numbers. Prefix the mask with FM to drop the padding: TO_CHAR(42, 'FM999').
How do I add a currency symbol?
Use $ for a literal dollar or L for the session's local currency symbol: TO_CHAR(total, 'FML99G999D00').
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.