How to keep 2 decimal places without rounding in php

hzc
Release: 2023-03-01 13:40:02
Original
9312 people have browsed it

How to keep 2 decimal places without rounding in php

How to keep 2 decimal places without rounding in php:

Keep 2 decimal places without rounding,

In fact we After understanding the characteristics of sprintf, we will keep one more decimal place after rounding, and then use substr to intercept the first two digits: the code is as follows

$n=0.1265489;
echo sprintf("%.2f",substr(sprintf("%.3f", $n), 0, -1));//0.12
Copy after login

PHP keeps two decimal places and rounds, and uses the sprintf function to perform $n Formatted %.2f is the target format, where 2 represents two digits and f represents float (floating point type). The third is a decimal 6 that is rounded;

$n=0.1265489;
echo sprintf("%.2f", $n); // 0.13
Copy after login

round function

<?PHP
  echo round(3.4);         // 3
  echo round(3.5);         // 4
  echo round(3.6);         // 4
  echo round(3.6, 0);      // 4
  echo round(1.95583, 2);  // 1.96
  echo round(1241757, -3); // 1242000
  echo round(5.045, 2);    // 5.05
  echo round(5.055, 2);    // 5.06
?>
Copy after login

Recommended tutorial: "php tutorial"

The above is the detailed content of How to keep 2 decimal places without rounding in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php.cn
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