Friday, December 20, 2024

MySQL ROUND() Function

 The ROUND() function in MySQL is used to round a number to a specified number of decimal places. The syntax of the function is:

ROUND(number, decimals)
  • number: The number to be rounded.
  • decimals: The number of decimal places to round the number to. If this parameter is omitted, the function will round the number to the nearest integer.

Example 1: Round a number to 2 decimal places

SELECT ROUND(123.4567, 2);

Output: 123.46

Example 2: Round a number to the nearest integer

SELECT ROUND(123.4567);

Output: 123

Example 3: Round a negative number to a specified decimal place

SELECT ROUND(-123.4567, 1);

Output: -123.5

Example 4: Round a number with a negative number of decimal places

If you pass a negative value for decimals, the function will round the number to the left of the decimal point.

SELECT ROUND(12345.6789, -2);

Output: 12300

In this case, the number is rounded to the nearest hundred (100).

Notes:

  • When decimals is not provided, MySQL rounds to the nearest integer.
  • The rounding behavior follows standard rounding rules, where numbers with a fractional part of .5 or greater are rounded up, and numbers with a fractional part less than .5 are rounded down.

No comments:

Post a Comment