STR
STR is a SQL function that converts a numeric value to a string type.
STR(number, length, decimals)
- number: This is the numerical value that we want to convert into a string. The number parameter must be a valid numeric or decimal value in MySQL.
- length: This is the total length of the string that will be returned. It includes the decimal point, all digits, signs, etc. If the string is shorter, it’s right-padded with spaces. If it’s longer, it’s truncated to the specified length.
- decimals: This parameter specifies the number of decimal places to be included in the output. This is counted as part of the total length of the string.
Example
Output
Explanation
In this example, STR
converts the number 5
into a string and then concatenates it with the string John Doe
. The result is a single string 5John Doe
.
STR( float_expression [ , length [ , decimal ] ] )
- float_expression: The floating-point number that needs to be converted into a string representation. This parameter is required.
- length: Defines the total length of the string that outside of the decimal point. Including signs, numbers, decimal points, and decimal numbers. If not specified, SQL Server defaults to 10.
- decimal: Specifies the number of digits to the right of the decimal point. If not specified, SQL Server defaults to 0. This parameter must be less than or equal to 16. If the number of decimal places is greater than the specified value, the value is rounded.
Example
Output
Explanation
The STR
function in SQL Server converts a numeric value to a string. The example uses STR
to convert the number 123.45
into a string with a length of 7
characters, including 2
digits after the decimal point. The result is '123.45'
, represented as a string.
STR(float_expression, integer_expression, integer_expression)
- float_expression: This parameter represents the floating point number that you wish to convert to a string.
- integer_expression: The first integer expression specifies the length of the output string. This includes the decimal point, digits, and signs. If the value is greater than 254, it will default to the maximum limit of 254.
- integer_expression: The second integer expression determines the number of digits that appear after the decimal point. If the value is negative, then the result will be rounded to the left side of the decimal point the same number of places. If the value is greater than 16, it will default to the maximum limit of 16.
Example
Output
Explanation
In this example, the STR
function is used to pad the string ‘Oracle’ with dots (’.’) until it reaches a total length of 10. The number 2 represents the decimal places present after padding. The output ‘Oracle…’ shows the applied padding.