Home  >  Article  >  Backend Development  >  How to Round Decimals Down to Two Decimal Places in PHP?

How to Round Decimals Down to Two Decimal Places in PHP?

DDD
DDDOriginal
2024-10-23 14:34:25214browse

How to Round Decimals Down to Two Decimal Places in PHP?

Rounding Decimals Down to Two Places in PHP

In PHP, rounding down a decimal to two decimal places can be challenging. While functions like number_format() round to the nearest point, methods like substr() fail to account for variable digit counts.

To achieve this rounding precision, consider the following solution:

<code class="php">$number = 49.955;
$rounded = floor($number * 100) / 100;

echo $rounded; // Output: 49.95</code>

Explanation:

  1. Multiply the number by 100 to shift the decimal point two places to the right.
  2. Use floor() to truncate the floating-point number, thereby rounding down any fractions.
  3. Divide the result by 100 to bring the decimal point back to its original position.

This method ensures accurate rounding down to two decimal places, regardless of the input number's starting value.

The above is the detailed content of How to Round Decimals Down to Two Decimal Places in PHP?. 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