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

DDD
Release: 2024-10-23 14:34:25
Original
211 people have browsed it

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>
Copy after login

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!

source:php
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!