Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String formatting in MySQL

Is there a printf()-like formatting in MySQL?
I couldn't find a straightforward way in the documentation.

For example, how can I make something like:

SELECT STRFORMATFUNCTIONIMLOOKINGFOR("%03d", 17) 

to get 017 ?

like image 731
Paul Oyster Avatar asked Mar 11 '09 07:03

Paul Oyster


People also ask

What is formatting in MySQL?

MySQL FORMAT() Function The FORMAT() function formats a number to a format like "#,###,###. ##", rounded to a specified number of decimal places, then it returns the result as a string.

How do I get 2 decimal places in MySQL?

SELECT ROUND(-4.535,2); Explanation: The above MySQL statement will round the given number -4.535 up to 2 decimal places.

How do I fix decimal places in MySQL?

MySQL ROUND() Function The ROUND() function rounds a number to a specified number of decimal places.

What is string function in MySQL?

Inserts a string within a string at the specified position and for a certain number of characters. INSTR. Returns the position of the first occurrence of a string in another string. LCASE. Converts a string to lower-case.


1 Answers

for your example, you could use

SELECT LPAD(17, 3, '0');

there is also

SELECT FORMAT(17, 3); -- 17.000

otherwise, UDF as mentioned above.

like image 54
ax. Avatar answered Oct 23 '22 21:10

ax.