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

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

Linda Hamilton
Linda HamiltonOriginal
2024-10-23 13:00:30347browse

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

PHP Number Formatting: Rounding Down to Two Decimal Places

Q: How do I round down a decimal number in PHP to two decimal places accurately?

A: To achieve this, you can utilize the following formula:

floor($number * 100) / 100

Let's break down the steps:

  1. Multiply the number by 100: This effectively shifts the decimal point two places to the right. For example, 49.955 becomes 4995.5.
  2. Apply the floor() function: The floor() function rounds the result down to the nearest whole number, discarding any fractional part. In our example, 4995.5 becomes 4995.
  3. Divide by 100: This shifts the decimal point back to its original position, resulting in 49.95.

Example:

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

This method ensures accurate rounding down to two decimal places, even for numbers smaller than 1.

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