Home  >  Article  >  Database  >  How to calculate division with decimals in SQL

How to calculate division with decimals in SQL

下次还敢
下次还敢Original
2024-05-01 22:33:15922browse

SQL division method to retain decimals: use CAST, ROUND or TRUNCATE function. The CAST function coerces a numeric type to preserve specific precision and scale. The ROUND function rounds floating point results. The TRUNCATE function truncates floating point results.

How to calculate division with decimals in SQL

Calculation method of decimal-preserving division in SQL

In SQL, the division operator is a slash (/ ), which produces a floating point result. By default, floating point results are rounded to 15 digits after the decimal point.

Methods for retaining decimal places

In order to retain more or fewer decimal places, you can use the following methods:

  • CAST function: Use this with the dividend or divisor to cast to a numeric type with specific precision and scale. For example:
<code class="sql">SELECT CAST(numerator AS DECIMAL(10, 2)) / CAST(denominator AS DECIMAL(10, 2));</code>
  • ROUND Function: is used to round floating point results. For example:
<code class="sql">SELECT ROUND(numerator / denominator, 2);</code>
  • TRUNCATE function: is used to truncate floating point results. For example:
<code class="sql">SELECT TRUNCATE(numerator / denominator, 2);</code>

Example

Consider the following query:

<code class="sql">SELECT 10 / 3;</code>

By default, this query returns a floating point result of 3.3333333333333335.

If you want to keep two decimal places, you can use the CAST function:

<code class="sql">SELECT CAST(10 AS DECIMAL(10, 2)) / CAST(3 AS DECIMAL(10, 2));</code>

This query will return 3.33.

The above is the detailed content of How to calculate division with decimals in SQL. 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