Home >Database >Mysql Tutorial >How Can I Format a Number to Display Exactly Two Decimal Places Without Rounding?

How Can I Format a Number to Display Exactly Two Decimal Places Without Rounding?

Linda Hamilton
Linda HamiltonOriginal
2024-12-05 11:57:111013browse

How Can I Format a Number to Display Exactly Two Decimal Places Without Rounding?

Formatting Numbers with Precise Decimal Control

When dealing with numerical data, it's often necessary to display numbers with a specific decimal format. In this case, the goal is to output a number with exactly two decimal places without rounding.

Problem: Find a method to format a number to display two decimal places without rounding the original value.

Example:

  • Input: 2229.999
  • Desired Output: 2229.99

Initial Attempts:

The attempts using the FORMAT and CONVERT functions were unsuccessful as they apply rounding instead of truncation.

Solution: Utilize the TRUNCATE Function

To achieve the desired behavior, we employ the TRUNCATE function, which truncates a number to a specified number of decimal places without rounding.

Examples:

Truncation (No Rounding):

TRUNCATE(0.166, 2) -- evaluates to 0.16
TRUNCATE(0.164, 2) -- evaluates to 0.16

Rounding:

The ROUND function can be used for rounding instead of truncation:

ROUND(0.166, 2) -- evaluates to 0.17
ROUND(0.164, 2) -- evaluates to 0.16

Documentation:

  • TRUNCATE: https://dev.mysql.com/doc/refman/8.0/en/mathematical-functions.html#function_truncate
  • ROUND: https://dev.mysql.com/doc/refman/8.0/en/mathematical-functions.html#function_round

The above is the detailed content of How Can I Format a Number to Display Exactly Two Decimal Places Without Rounding?. 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