To convert a number to a string in PostgreSQL, use the CAST function (CAST(number AS TEXT)) or the shorter ::text syntax (number::text). For formatted output (e.g., with commas or decimal places), use TO_CHAR(number, 'format').
Why Convert Numbers to Strings in PostgreSQL
Converting numeric values to text is a routine task in SQL queries and application development. Common reasons include:
- Concatenation: Combining a number with a string using the
||operator requires the number to be text first. - Display formatting: You may want to show a price as “$1,234.56” or a percentage as “12.3%” rather than a raw numeric value.
- Data export: When generating CSV or JSON output, numeric values are often converted to strings to control precision or avoid scientific notation.
- Joining on mixed types: If a column is stored as text but contains numeric-looking data, you may need to convert a number to match for a join.
The Basic Cast: CAST and ::text
PostgreSQL supports two equivalent syntaxes for type conversion:
CAST(expression AS target_type)– the SQL standard.expression::target_type– a PostgreSQL-specific shorthand.
For converting a number to text, the target type is TEXT. Example:
SELECT CAST(12345 AS TEXT); -- returns '12345'
SELECT 12345::text; -- also returns '12345'
Both work for integers, decimals, and floating-point numbers. For a numeric column named amount in a table, you would write:
SELECT amount::text FROM orders;
Formatting Numbers with TO_CHAR
When you need specific formatting—like thousands separators, currency symbols, or a fixed number of decimal places—use TO_CHAR. It takes a number and a format pattern and returns a string.
Common format patterns:
FM999G999D99– usesGfor group separator (comma) andDfor decimal point, withFMto remove leading spaces.L999G999D99– adds the locale currency symbol (e.g.,$).999.99– fixed decimal places, but note the decimal point is a literal dot.
Example:
SELECT TO_CHAR(1234567.89, 'FM999G999D99'); -- returns '1,234,567.89'
SELECT TO_CHAR(0.5, 'FM999.00'); -- returns '0.50'
Be careful: TO_CHAR with a pattern that has fewer digits than the number will show # signs instead of truncating. For instance, TO_CHAR(12345, '999') returns '#####'.
Implicit Conversion in Concatenation
PostgreSQL does not automatically convert numbers to strings when using ||. If you try SELECT 'Order ' || 42;, you get an error: operator is not unique: unknown || integer. You must cast explicitly:
SELECT 'Order ' || 42::text; -- returns 'Order 42'
In practice, many developers use CONCAT() function, which does implicit conversion:
SELECT CONCAT('Order ', 42); -- returns 'Order 42'
However, CONCAT ignores NULL arguments, whereas || with a NULL returns NULL. Choose based on your NULL-handling needs.
Common Pitfalls and Edge Cases
Several issues trip up users when converting numbers to strings:
- Scientific notation: For
double precisionvalues, casting to text may produce scientific notation for very large or very small numbers. Example:SELECT 1e20::text;returns'1e+20'. UseTO_CHARwith a format like'FM999999999999999999999'to force plain notation. - Trailing zeros: Casting a
numericlike1.50to text gives'1.50'(preserves scale), but casting adouble precision1.5 gives'1.5'(may drop trailing zeros). - Locale differences:
TO_CHARuses the database’s locale for group and decimal separators. If your database is set to a European locale,Gmight be a dot andDa comma. You can force a specific separator by using literal characters in the pattern, e.g.,'FM999,999.99'. - Leading spaces: By default,
TO_CHARpads the result with spaces to match the pattern width. TheFMprefix (Fill Mode) removes those spaces.
Performance and Indexing Considerations
Converting a number to a string in a WHERE clause can prevent index usage. For example, if you have an index on a numeric column id and you write WHERE id::text = '123', PostgreSQL cannot use a regular b-tree index on id because the expression is not the column itself. Instead, consider storing the number as text if you frequently need string matching, or use a functional index:
CREATE INDEX idx_orders_id_text ON orders ((id::text));
In practice, such conversions are rare in WHERE clauses; they are more common in SELECT lists and JOIN conditions. For large exports, converting many rows can add CPU overhead, but it is usually negligible compared to I/O.
Alternatives: Using the text() Function and Other Types
Besides CAST and ::text, you can use the text() function, which is a built-in conversion function:
SELECT text(12345); -- returns '12345'
This is functionally identical to CAST(12345 AS TEXT). For special cases, consider:
- Converting to
VARCHAR(n): UseCAST(number AS VARCHAR(10))if you need a limited length, but note that it will throw an error if the string exceeds the length. - Using
FORMAT(): TheFORMAT()function can also format numbers, e.g.,SELECT FORMAT('%s', 12345);returns'12345', but it is more verbose for simple casts. - JSON conversion: If you need a JSON string representation,
to_json(number)returns a JSON number, not a string. To get a JSON string, cast first:to_json(number::text).
Frequently Asked Questions
How do I convert a number to a string with two decimal places?
Use TO_CHAR(number, 'FM999.00') to get exactly two decimal places. For example, TO_CHAR(12.5, 'FM999.00') returns '12.50'. If you want a comma as decimal separator, adjust the pattern or locale.
Why does my number convert to scientific notation?
This happens with double precision values when the number is very large or very small. Casting to text uses the shortest representation that round-trips, which can be scientific. To force plain notation, use TO_CHAR with a format that has enough digits, or cast to numeric first: (1e20::numeric)::text returns '100000000000000000000'.
Can I convert a string back to a number?
Yes, use CAST(string AS INTEGER) or string::numeric. For example, '123'::int returns 123. Be aware that invalid strings will raise an error; use NULLIF or a CASE statement to handle bad input gracefully.
What is the difference between ::text and ::varchar?
Both produce a string type. TEXT has no length limit, while VARCHAR(n) has a maximum length. For most purposes, ::text is preferred because it avoids accidental truncation errors. If you need a specific length for a column definition, use VARCHAR(n).
Does TO_CHAR work with negative numbers?
Yes, but the minus sign is placed according to the pattern. With FM999, a negative number like -123 returns '-123'. If you want parentheses for negatives (accounting style), use the S or PR pattern, e.g., TO_CHAR(-123, 'FM999PR') returns '<123>'.
Related
- What Is enum in Java? Definition & Usage
- How to Update a Dictionary in Python
- Value Dollar Shop Jurong East: Location, Prices & What to Expect
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Excel Power Query: Add Data to an Existing Table?Yes—use Power Query’s Append operation to combine rows from an existing table and another data source, then load…
- How to Make a Flowchart in Word Easily, Step by StepTo make a flowchart in Microsoft Word, choose Insert > Shapes, select a shape from the Flowchart section,…
- String in Java: Meaning, Methods, and ExamplesIn Java, String is the standard class for representing text, such as names, messages, and file paths. It…
- Excel RANK vs RANK.EQ: Differences, Ties, and ExamplesRANK and RANK.EQ return the same result in current Excel: each gives a number’s position in a list,…
- SMALL in Excel: Find the Nth Smallest Value with ExamplesIn Excel, use the SMALL function to return the 1st, 2nd, 3rd, or any other chosen smallest number…
- Where Is the Superscript Button in Excel?In Excel for Microsoft 365 on Windows, the superscript option is in the Format Cells dialog, not on…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.