How to keep 2 decimal places without rounding in php

hzc
Release: 2023-03-01 13:40:02
Original
9116 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

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