Home > Database > SQL > body text

How to calculate division with decimals in SQL

下次还敢
Release: 2024-05-01 22:33:15
Original
883 people have browsed it

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>
Copy after login
  • ROUND Function: is used to round floating point results. For example:
<code class="sql">SELECT ROUND(numerator / denominator, 2);</code>
Copy after login
  • TRUNCATE function: is used to truncate floating point results. For example:
<code class="sql">SELECT TRUNCATE(numerator / denominator, 2);</code>
Copy after login

Example

Consider the following query:

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

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>
Copy after login

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!

source:php.cn
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!