search
HomeBackend DevelopmentPHP ProblemHow to keep 2 decimal places without rounding in php

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

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

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
?>

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools