T-SQL STR() Function
The T-SQL (Transact-SQL) STR() function returns a string representation of a numeric value. The string representation is right-justified, with a specified length and decimal precision.
Syntax
STR(number [, length [, decimal ] ])
Parameters
number |
Required. Specify the numeric value to convert to a string. |
length |
Optional. Specify the length of the resulting string which includes all digits, decimals, signs, etc. If it is not specified, it will default to 10. |
decimal |
Optional. Specify the number of decimal places to display in the resulting string and can not exceed 16. If it is not specified, it will default to 0. If decimal is more than 16 then the result is truncated to sixteen places to the right of the decimal point. |
Return Value
Returns a string representation of a numeric value.
Example 1:
The example below shows the usage of STR() function.
SELECT STR(1234); Result: '1234' SELECT STR(1234.5678); Result: '1235' SELECT STR(1234.5678, 7); Result: '1235' SELECT STR(1234.5678, 7, 1); Result: '1234.6' SELECT STR(1234.5678, 7, 2); Result: '1234.57' SELECT STR(1234.5678, 8, 3); Result: '1234.568'
Example 2:
Consider a database table called Sample with the following records:
Data | x |
---|---|
Data 1 | -3.75567 |
Data 2 | -5.3867 |
Data 3 | 13.9804 |
Data 4 | 93.1601 |
Data 5 | 48.1322 |
The statement given below can be used to convert the numeric value into its string representation with specified length and decimal precision.
SELECT *, STR(x, 5, 2) AS STR_Value FROM Sample;
This will produce the result as shown below:
Data | x | STR_Value |
---|---|---|
Data 1 | -3.75567 | -3.76 |
Data 2 | -5.3867 | -5.39 |
Data 3 | 13.9804 | 13.98 |
Data 4 | 93.1601 | 93.16 |
Data 5 | 48.1322 | 48.13 |
❮ T-SQL Functions