SQL Server STR function
STR(123.456, 8, 2) returns ' 123.46': a float rendered at a fixed width with a fixed number of decimals.
- Category
- Conversion
- Returns
varchar- In this category
- 39 of 39
Syntax
STR(float_expression [, length [, decimal]])
Engine support
| Engine | Support | Notes |
|---|---|---|
| SQL Server | Yes | Supported under this name. |
| PostgreSQL | Different name or syntax | to_char(x, '99990.00') pads to the mask |
| MySQL | Different name or syntax | LPAD(FORMAT(x, 2), 8, ' '), though FORMAT adds thousands separators |
| SQLite | Different name or syntax | printf('%8.2f', x) |
| Oracle | Different name or syntax | TO_CHAR(x, '99990.00') or LPAD(TO_CHAR(x), n) |
Examples
SQL Server
SELECT STR(123.456, 8, 2) AS padded, LTRIM(STR(123.456, 8, 2)) AS trimmed; -- ' 123.46', '123.46'
SQL Server
SELECT STR(1234567, 5) AS too_wide, REPLACE(STR(42, 6), ' ', '0') AS zero_padded; -- '*****', '000042'
SQLite
SELECT printf('%8.2f', 123.456) AS padded; -- ' 123.46'
Good to know
- The default length is 10 with no decimals, padded with leading spaces: '[' + STR(42) + ']' is '[ 42]'. Wrap it in LTRIM when you only want the digits.
- The argument is converted to float first, so STR(1.005, 5, 2) returns ' 1.00': 1.005 is stored as 1.00499... in binary.
- A number that does not fit the length comes back as asterisks: STR(1234567, 5) is '*****'.
- STR rounds half away from zero: STR(0.5) is 1 and STR(-1.5) is -2, each padded to 10 characters.
Questions about STR
STR or FORMAT?
STR is fixed-width and does not care about culture. FORMAT uses .NET format strings and the session language, and it is much slower over many rows. For plain text without padding, CAST(x AS varchar) is enough.
How do I zero-pad with STR?
Replace the padding: REPLACE(STR(42, 6), ' ', '0') gives '000042'. It breaks on negative numbers, where the minus sign ends up after the zeros.
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.