How the ROUND() function works in Mariadb?

The ROUND() function in MariaDB is a numeric function that rounds a number to a specified number of decimal places.

Posted on

The ROUND() function in MariaDB is a numeric function that rounds a number to a specified number of decimal places. It is a commonly used function in MariaDB for various mathematical and data manipulation tasks. This article will explain the syntax of the ROUND() function, demonstrate its usage with various examples, and explore related functions that offer similar or complementary functionality.

Syntax

The basic syntax of the ROUND() function is as follows:

ROUND(X [, D])

Where:

  • X is the number to be rounded. It can be a numeric literal, a column name, or an expression.
  • D is the number of decimal places to which the number should be rounded. If D is positive, the number is rounded to the specified number of decimal places to the right of the decimal point. If D is negative, the number is rounded to the specified number of decimal places to the left of the decimal point. If D is omitted, the number is rounded to the nearest integer.

Examples

Rounding to the nearest integer

The following example rounds the number 3.14159 to the nearest integer:

SELECT ROUND(3.14159);

The output of the above query is:

3

Rounding to two decimal places

The following example rounds the number 3.14159 to two decimal places:

SELECT ROUND(3.14159, 2);

The output of the above query is:

3.14

Rounding to a negative number of decimal places

The following example rounds the number 12345.6789 to two decimal places to the left of the decimal point:

SELECT ROUND(12345.6789, -2);

The output of the above query is:

12300

Rounding a negative number

The following example rounds the number -3.14159 to the nearest integer:

SELECT ROUND(-3.14159);

The output of the above query is:

-3

The following functions are related to the ROUND() function:

  • CEIL(): This function rounds a number up to the nearest integer.
  • FLOOR(): This function rounds a number down to the nearest integer.
  • TRUNCATE(): This function truncates a number to a specified number of decimal places.

Conclusion

The ROUND() function is a versatile and useful function for rounding numbers in MariaDB. It can be used for a variety of tasks, such as formatting data for display, performing mathematical calculations, and implementing rounding rules in business logic. By understanding the syntax and usage of the ROUND() function, you can effectively manipulate numeric data in your MariaDB database.