PostgreSQL – TO_NUMBER Function
The TO_NUMBER
function is used to convert a string representation of a number into a numeric data type. It’s particularly useful when you have numeric values stored as strings and you want to convert them into actual numeric values for arithmetic operations or comparisons.
The syntax of the TO_NUMBER
function is as follows:
TO_NUMBER(string, format)
Below is an example of using the TO_NUMBER
function to convert a string into a number:
SELECT TO_NUMBER('12345.67', '99999.99') AS converted_number;
In this example, the string ‘12345.67’ is converted into a numeric value using the ‘99999.99’ format.
You can also use the TO_NUMBER
function to handle numbers with different formats:
SELECT TO_NUMBER('12,345.67', '99,999.99') AS converted_number;
Here, the string ‘12,345.67’ is converted into a numeric value using the ‘99,999.99’ format.
Keep in mind that the second argument of the TO_NUMBER
function (format
) specifies the expected format of the input string so that PostgreSQL can correctly interpret and convert it into a numeric value.
The TO_NUMBER
function is particularly useful when dealing with data that’s stored as strings but needs to be treated as numbers for calculations, aggregations, or comparisons.