Home > Database > Mysql Tutorial > body text

How to format a number to two decimal places in MySQL?

WBOY
Release: 2023-09-10 18:01:26
forward
807 people have browsed it

How to format a number to two decimal places in MySQL?

You can use MySQL's TRUNCATE() function to format a number to 2 decimal places. The syntax is as follows:

SELECT TRUNCATE(yourColumnName,2) as anyVariableName from yourTableName;
Copy after login

In order to understand the above syntax, let us first create a table. The query to create the table is as follows -

mysql> create table FormatNumberTwoDecimalPlace
   -> (
   -> Number float
   -> );
Query OK, 0 rows affected (0.59 sec)
Copy after login

Use the insert command to insert some records in the table. The query is as follows −

mysql> insert into FormatNumberTwoDecimalPlace values(123.456);
Query OK, 1 row affected (0.13 sec)

mysql> insert into FormatNumberTwoDecimalPlace values(1.6789);
Query OK, 1 row affected (0.19 sec)

mysql> insert into FormatNumberTwoDecimalPlace values(12.2);
Query OK, 1 row affected (0.14 sec)

mysql> insert into FormatNumberTwoDecimalPlace values(12356.23145);
Query OK, 1 row affected (0.40 sec)

mysql> insert into FormatNumberTwoDecimalPlace values(12356);
Query OK, 1 row affected (0.14 sec)

mysql> insert into FormatNumberTwoDecimalPlace values(.5678);
Query OK, 1 row affected (0.28 sec)
Copy after login

Let us now use the select command to display all the records in the table. The query looks like this −

mysql> select *from FormatNumberTwoDecimalPlace;
Copy after login

Output

+---------+
| Number  |
+---------+
| 123.456 |
|  1.6789 |
|    12.2 |
| 12356.2 |
|   12356 |
|  0.5678 |
+---------+
6 rows in set (0.04 sec)
Copy after login

This is the query to format a number to two decimal places −

mysql> select truncate(Number,2) as TwoValueAfterDecimal from
FormatNumberTwoDecimalPlace;
Copy after login

Output

+----------------------+
| TwoValueAfterDecimal |
+----------------------+
|               123.45 |
|                 1.67 |
|                12.19 |
|             12356.23 |
|             12356.00 |
|                 0.56 |
+----------------------+
6 rows in set (0.00 sec)
Copy after login

The above is the detailed content of How to format a number to two decimal places in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!