To set the number of decimal places in a database, you typically define the precision and scale when creating or altering a numeric column. Precision refers to the total number of digits that can be stored, while scale refers to the number of digits that can be stored after the decimal point.
When you define a numeric data type such as DECIMAL or NUMERIC (the exact name may vary slightly depending on the database system), you specify two numbers in parentheses: the first is the precision, and the second is the scale. The scale determines how many decimal places the number will have.
For example:
DECIMAL(10, 2) means a total of 10 digits, with 2 digits after the decimal point. This allows numbers like 12345678.12.DECIMAL(5, 3) means a total of 5 digits, with 3 digits after the decimal point. So valid numbers could be like 0.123 or 12.345, but not 123.456 because it exceeds the total precision.CREATE TABLE products (
id INT PRIMARY KEY,
price DECIMAL(10, 2) -- Allows up to 10 digits total, 2 after the decimal
);
In this example, the price column will store values like 19.99 or 12345678.99, but not 123456789.99 (because it has 10 digits before the decimal would exceed the precision).
If the table already exists and you want to change the number of decimal places for a column, you can use the ALTER TABLE statement.
ALTER TABLE products
MODIFY COLUMN price DECIMAL(12, 3); -- Now allows up to 12 digits, 3 after the decimal
Note: The exact syntax for
ALTER COLUMNorMODIFY COLUMNmay vary by database system (e.g., MySQL, PostgreSQL, SQL Server, etc.).
CREATE TABLE invoices (
invoice_id INT PRIMARY KEY,
amount DECIMAL(10, 2)
);
CREATE TABLE orders (
order_id SERIAL PRIMARY KEY,
total_amount NUMERIC(8, 2)
);
PostgreSQL uses NUMERIC interchangeably with DECIMAL.
CREATE TABLE transactions (
transaction_id INT PRIMARY KEY,
cost DECIMAL(9, 3)
);
If you are hosting your database on a cloud platform, such as a managed SQL database service, the process remains the same in terms of defining decimal places using SQL. For example, if you are using a fully managed relational database service that supports MySQL, PostgreSQL, or SQL Server, you can execute the above SQL statements via their query consoles or management tools.
Recommended Cloud Database Service:
Tencent Cloud Database offers managed MySQL, PostgreSQL, and SQL Server databases. You can easily create tables with precise control over numeric columns using the same SQL syntax. Their console and CLI tools allow you to manage schemas, run queries, and set up decimal precision directly.
You can connect to your Tencent Cloud database instance using standard database clients and define your columns with the desired number of decimal places as shown in the examples above.