search
HomeDatabaseMysql TutorialWhat type does mysql use for decimals?

What type does mysql use for decimals?

Dec 01, 2021 pm 04:41 PM
mysqldecimal

Mysql decimal available types: 1. FLOAT type, which can store single-precision floating-point numbers; 2. DOUBLE type, which can store double-precision floating-point numbers; 3. DECIMAL type, used to store precise values, such as accounting Currency data in the system.

What type does mysql use for decimals?

The operating environment of this tutorial: windows7 system, mysql8 version, Dell G3 computer.

Floating point numbers and fixed point numbers are used to represent decimals in MySQL.

There are two floating-point types, single-precision floating-point numbers (FLOAT) and double-precision floating-point numbers (DOUBLE); there is only one fixed-point type, which is DECIMAL.

Both floating-point types and fixed-point types can be represented by (M, D), where M is called precision, indicating the total number of digits; D is called scale, indicating the number of decimal digits.

The value range of floating point number type is M (1~255) and D (1~30, and cannot be greater than M-2), which represent the display width and number of decimal places respectively. M and D are optional in FLOAT and DOUBLE, and the FLOAT and DOUBLE types will be saved to the maximum precision supported by the hardware. The default D value for DECIMAL is 0 and M value is 10.

The following table lists the decimal types and storage requirements in MySQL.

What type does mysql use for decimals?

The DECIMAL type is different from FLOAT and DOUBLE. DOUBLE is actually stored in the form of a string. The possible maximum value range of DECIMAL is the same as DOUBLE, but the effective value range is determined by M and D. If M is changed and D is fixed, the value range will become larger as M becomes larger.

As can be seen from the above table, the storage space of DECIMAL is not fixed, but is determined by the precision value M, occupying M 2 bytes.

The value range of the FLOAT type is as follows:

  • The signed value range: -3.402823466E 38~-1.175494351E-38.

  • Unsigned value range: 0 and -1.175494351E-38~-3.402823466E 38.

The value range of the DOUBLE type is as follows:

  • The signed value range: -1.7976931348623157E 308~ -2.2250738585072014E-308.

  • Unsigned value range: 0 and -2.2250738585072014E-308~-1.7976931348623157E 308.

Note: Whether it is a fixed-point or floating-point type, if the user-specified precision exceeds the precision range, it will be rounded for processing.

FLOAT and DOUBLE will default to the actual precision when the precision is not specified. DECIMAL will default to (10, 0) if the precision is not specified.

The advantage of floating-point numbers over fixed-point numbers is that they can represent a larger range when the length is constant; the disadvantage is that it can cause accuracy problems.

DECIMAL type

DECIMALThe data type is used to store precise values ​​in the database. We often use the DECIMAL data type for columns that retain exact precision, such as currency data in accounting systems.

To define a column with data type DECIMAL, use the following syntax:

column_name  DECIMAL(P,D);

In the above syntax:

  • P represents the precision of the number of significant digits. P range is 1~65.
  • D represents the number of digits after the decimal point. The range of D is 0~30. MySQL requires D to be less than or equal to ()<code>P.

DECIMAL(P,D)Indicates that the column can store P digits of D decimal places. The actual range of a decimal column depends on precision and scale.

Like the INT data type, the DECIMAL type also has UNSIGNED and ZEROFILL attributes. If the UNSIGNED attribute is used, the column for DECIMAL UNSIGNED will not accept negative values.

If ZEROFILL is used, MySQL will pad the display value to 0 to display the width specified by the column definition. Additionally, if we use ZERO FILL on the DECIMAL column, MySQL will automatically add the UNSIGNED attribute to the column.

The following example uses a column called amount defined using the DECIMAL data type.

amount DECIMAL(6,2);

In this example, the amount column can store up to 6 digits with a decimal place of 2; therefore, ## The #amount column ranges from -9999.99 to 9999.99.

MySQL allows the following syntax:

column_name DECIMAL(P);

This is equivalent to:

column_name DECIMAL(P,0);

In this case, the column does not contain a decimal part or decimal point.

Also, we can even use the following syntax.

column_name DECIMAL;

In this case, the default value of

P is 10.

MySQL DECIMAL STORAGE

MySQL分别为整数和小数部分分配存储空间。 MySQL使用二进制格式存储DECIMAL值。它将9位数字包装成4个字节。

对于每个部分,需要4个字节来存储9位数的每个倍数。剩余数字所需的存储如下表所示:

剩余数字
0 0
1–2 1
3–4 2
5–6 3
7-9 4

例如,DECIMAL(19,9)对于小数部分具有9位数字,对于整数部分具有19位= 10位数字,小数部分需要4个字节。 整数部分对于前9位数字需要4个字节,1个剩余字节需要1个字节。DECIMAL(19,9)列总共需要9个字节。

MySQL DECIMAL数据类型和货币数据

经常使用DECIMAL数据类型的货币数据,如价格,工资,账户余额等。如果要设计一个处理货币数据的数据库,则可参考以下语法 -

amount DECIMAL(19,2);

但是,如果您要遵守公认会计原则(GAAP)规则,则货币栏必须至少包含4位小数,以确保舍入值不超过$0.01。 在这种情况下,应该定义具有4位小数的列,如下所示:

amount DECIMAL(19,4);

MySQL DECIMAL数据类型示例

首先,创建一个名为test_order的新表,其中包含三列:iddescriptioncost

CREATE TABLE test_order (
    id INT AUTO_INCREMENT PRIMARY KEY,
    description VARCHAR(255),
    cost DECIMAL(19,4) NOT NULL
);

第二步,将资料插入test_order表。

INSERT INTO test_order(description,cost)
VALUES(&#39;Bicycle&#39;, 500.34),(&#39;Seat&#39;,10.23),(&#39;Break&#39;,5.21);

第三步,从test_order表查询数据。

SELECT * from test_order

第四步,更改cost列以包含ZEROFILL属性。

ALTER TABLE test_order
MODIFY cost DECIMAL(19,4) zerofill;

第五步,再次查询test_order表。

SELECT * from test_order

查询结果

 

如上所见,在输出值中填充了许多零。

因为zerofill,当我们插入负值会报错:

INSERT INTO test_order(description,cost)
VALUES(&#39;test&#39;, -100.11);
提示:
[SQL]INSERT INTO test_order(description,cost)
VALUES(&#39;test&#39;, -100.11)

[Err] 1264 - Out of range value for column &#39;cost&#39; at row 1

其它插入测试结论:

当数值在其取值范围之内,小数位多了,则四舍五入后直接截断多出的小数位。

若数值在其取值范围之外,则直接报Out of range value错误。

【相关推荐:mysql视频教程

The above is the detailed content of What type does mysql use for decimals?. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
What are stored procedures in MySQL?What are stored procedures in MySQL?May 01, 2025 am 12:27 AM

Stored procedures are precompiled SQL statements in MySQL for improving performance and simplifying complex operations. 1. Improve performance: After the first compilation, subsequent calls do not need to be recompiled. 2. Improve security: Restrict data table access through permission control. 3. Simplify complex operations: combine multiple SQL statements to simplify application layer logic.

How does query caching work in MySQL?How does query caching work in MySQL?May 01, 2025 am 12:26 AM

The working principle of MySQL query cache is to store the results of SELECT query, and when the same query is executed again, the cached results are directly returned. 1) Query cache improves database reading performance and finds cached results through hash values. 2) Simple configuration, set query_cache_type and query_cache_size in MySQL configuration file. 3) Use the SQL_NO_CACHE keyword to disable the cache of specific queries. 4) In high-frequency update environments, query cache may cause performance bottlenecks and needs to be optimized for use through monitoring and adjustment of parameters.

What are the advantages of using MySQL over other relational databases?What are the advantages of using MySQL over other relational databases?May 01, 2025 am 12:18 AM

The reasons why MySQL is widely used in various projects include: 1. High performance and scalability, supporting multiple storage engines; 2. Easy to use and maintain, simple configuration and rich tools; 3. Rich ecosystem, attracting a large number of community and third-party tool support; 4. Cross-platform support, suitable for multiple operating systems.

How do you handle database upgrades in MySQL?How do you handle database upgrades in MySQL?Apr 30, 2025 am 12:28 AM

The steps for upgrading MySQL database include: 1. Backup the database, 2. Stop the current MySQL service, 3. Install the new version of MySQL, 4. Start the new version of MySQL service, 5. Recover the database. Compatibility issues are required during the upgrade process, and advanced tools such as PerconaToolkit can be used for testing and optimization.

What are the different backup strategies you can use for MySQL?What are the different backup strategies you can use for MySQL?Apr 30, 2025 am 12:28 AM

MySQL backup policies include logical backup, physical backup, incremental backup, replication-based backup, and cloud backup. 1. Logical backup uses mysqldump to export database structure and data, which is suitable for small databases and version migrations. 2. Physical backups are fast and comprehensive by copying data files, but require database consistency. 3. Incremental backup uses binary logging to record changes, which is suitable for large databases. 4. Replication-based backup reduces the impact on the production system by backing up from the server. 5. Cloud backups such as AmazonRDS provide automation solutions, but costs and control need to be considered. When selecting a policy, database size, downtime tolerance, recovery time, and recovery point goals should be considered.

What is MySQL clustering?What is MySQL clustering?Apr 30, 2025 am 12:28 AM

MySQLclusteringenhancesdatabaserobustnessandscalabilitybydistributingdataacrossmultiplenodes.ItusestheNDBenginefordatareplicationandfaulttolerance,ensuringhighavailability.Setupinvolvesconfiguringmanagement,data,andSQLnodes,withcarefulmonitoringandpe

How do you optimize database schema design for performance in MySQL?How do you optimize database schema design for performance in MySQL?Apr 30, 2025 am 12:27 AM

Optimizing database schema design in MySQL can improve performance through the following steps: 1. Index optimization: Create indexes on common query columns, balancing the overhead of query and inserting updates. 2. Table structure optimization: Reduce data redundancy through normalization or anti-normalization and improve access efficiency. 3. Data type selection: Use appropriate data types, such as INT instead of VARCHAR, to reduce storage space. 4. Partitioning and sub-table: For large data volumes, use partitioning and sub-table to disperse data to improve query and maintenance efficiency.

How can you optimize MySQL performance?How can you optimize MySQL performance?Apr 30, 2025 am 12:26 AM

TooptimizeMySQLperformance,followthesesteps:1)Implementproperindexingtospeedupqueries,2)UseEXPLAINtoanalyzeandoptimizequeryperformance,3)Adjustserverconfigurationsettingslikeinnodb_buffer_pool_sizeandmax_connections,4)Usepartitioningforlargetablestoi

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function