Home >Database >Mysql Tutorial >How Can I Precisely Format Numbers to Two Decimal Places in MySQL without Rounding?
Precisely Formatting Numbers with Two Decimal Places
In the realm of programming, it's crucial to effectively represent numerical values. One common requirement is to output a number with two decimal places, without compromising its original precision.
Consider the example:
2229,999 -> 2229,99
To address this, let's explore the concept of truncation.
Understanding Truncation
Truncation is a mathematical operation that removes fractional digits from a number without rounding. This preserves the original value but eliminates the unwanted decimals.
Utilizing the TRUNCATE Function
In MySQL, we can use the TRUNCATE function to achieve truncation. The syntax is:
TRUNCATE(number, decimal_places)
Where:
Examples:
To output 2229,999 with two decimal places:
TRUNCATE(2229.999, 2)
This expression evaluates to 2229,99, preserving the original precision.
Differentiating from ROUNDing
Unlike TRUNCATE, ROUNDing adjusts the value to the nearest decimal place. The ROUND function is useful for approximating values, but it may alter the original number.
For reference, here are the ROUND example uses:
ROUND(0.166, 2) -> 0.17 (rounded up) ROUND(0.164, 2) -> 0.16 (rounded down)
Conclusion
When seeking to format numbers precisely with two decimal places, the TRUNCATE function offers an effective solution. It retains the original value's accuracy while truncating unwanted decimal digits.
The above is the detailed content of How Can I Precisely Format Numbers to Two Decimal Places in MySQL without Rounding?. For more information, please follow other related articles on the PHP Chinese website!