w3resource

MySQL FORMAT() function

FORMAT() function

MySQL FORMAT() converts a number to a format like ‘#,###,###.##’ which is rounded upto the number of decimal places specified (in the second argument) and returns the result as a string. There is no decimal point if the decimal place is defined as 0.

This function is useful in -

  • Number formatting: Use it to format numerical values with decimal places and thousands separators.
  • Currency display: FORMAT() can be used to format numeric values as currency amounts.

Syntax:

FORMAT (N, D)

Arguments:

Name Description
N A number which may be an integer, a decimal or a double.
D An integer which specifies up to how many decimal places the return value is going to contain.

MySQL Version: 8.0

Pictorial Presentation:

MySQL FORMAT() pictorial presentation

Example : MySQL FORMAT() function

The following MySQL statement calculates up to 3 decimal places of 12324.2573, so it returns 12,324.257.

Code:

SELECT FORMAT(12324.2573,3);

Output:

mysql> SELECT FORMAT(12324.2573,3);
+----------------------+
| FORMAT(12324.2573,3) |
+----------------------+
| 12,324.257           | 
+----------------------+
1 row in set (0.02 sec)

Example of MySQL format() function using where clause

The following statement will return those books from the book_mast table, whose prices are more than 150. The price is returned up to 4 decimal places as specified in the argument.

Code:

SELECT book_name,FORMAT(book_price,4) 
FROM book_mast
WHERE book_price>150;

Sample table: book_mast


Output:

mysql> SELECT book_name,FORMAT(book_price,4) 
    -> FROM book_mast
    -> WHERE book_price>150;
+--------------------------------+----------------------+
| book_name                      | FORMAT(book_price,4) |
+--------------------------------+----------------------+
| Guide to Networking            | 200.0000             | 
| Transfer  of Heat and Mass     | 250.0000             | 
| Fundamentals of Thermodynamics | 225.0000             | 
| Concepts in Health             | 180.0000             | 
+--------------------------------+----------------------+
4 rows in set (0.05 sec)

Video Presentation:

All String Functions (Slides presentation)

Previous: FIND_IN_SET
Next: HEX



Follow us on Facebook and Twitter for latest update.