Home > Database > Mysql Tutorial > How Can I Truncate Numbers to Exactly Two Decimal Places in MySQL Without Rounding?

How Can I Truncate Numbers to Exactly Two Decimal Places in MySQL Without Rounding?

Susan Sarandon
Release: 2024-12-22 04:18:17
Original
293 people have browsed it

How Can I Truncate Numbers to Exactly Two Decimal Places in MySQL Without Rounding?

Truncating Numbers to Preserved Exact Values with Two Decimal Places

When working with numbers, it's often necessary to format them to a specific precision. In this particular case, you're interested in displaying numbers with exactly two decimal places, without rounding.

The key to achieving this is to use the TRUNCATE function, which removes digits from the end of a number without performing any rounding. For example:

TRUNCATE(2229.999, 2)
Copy after login

This expression would result in "2229.99", preserving the exact value without rounding it up to "2230.00".

To understand the difference from rounding, consider the following examples:

ROUND(0.166, 2)
-- Results in 0.17 (rounded up)

TRUNCATE(0.166, 2)
-- Results in 0.16 (truncated)
Copy after login

As you can see, the TRUNCATE function maintains the original value without introducing any rounding errors.

Here is the official MySQL documentation for the TRUNCATE function:

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

The above is the detailed content of How Can I Truncate Numbers to Exactly Two Decimal Places in MySQL Without Rounding?. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template