// conversion reference

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.

Categoria
Conversion
Returns
varchar
In this category
39 of 39

Sintaxe

STR(float_expression [, length [, decimal]])

Suporte a mecanismos

MotorSupportNotas
SQL Server Sim 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)

Exemplos

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'

Bom saber

  • 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.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// fewer lookups

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.