Cover Image for MySQL DECIMAL
110 views

MySQL DECIMAL

The MySQL DECIMAL data type is used to store fixed-point numbers, which are numbers with a fixed number of digits to the right of the decimal point. This is different from the FLOAT and DOUBLE data types, which are used to store floating-point numbers with a varying number of decimal places.

The DECIMAL data type is commonly used when precision and exact numeric representation are important, such as in financial applications or any situation where you need to avoid rounding errors.

Here’s the basic syntax for defining a DECIMAL column in a MySQL table:

column_name DECIMAL(p, s);
  • column_name: The name of the column.
  • p: The total number of digits, including both the digits to the left and right of the decimal point. This is the precision.
  • s: The number of digits to the right of the decimal point. This is the scale.

For example, if you want to create a table to store prices of products with a maximum of 2 decimal places (e.g., $12.34), you can define a DECIMAL column like this:

CREATE TABLE products (
    product_id INT,
    product_name VARCHAR(255),
    price DECIMAL(6, 2)
);

In this example, the price column is defined as DECIMAL(6, 2). This means it can store up to 6 digits in total, with 2 digits to the right of the decimal point.

Here are some sample values you could store in this price column:

  • 12.34 (Valid)
  • 123.45 (Valid)
  • 1.00 (Valid)
  • 123456.78 (Invalid, exceeds the total number of digits allowed)

MySQL’s DECIMAL data type allows you to work with fixed-point numbers precisely and is suitable for scenarios where you need to maintain exact numeric values without rounding errors.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS