Home > Backend Development > PHP Problem > How to output numbers with two decimal places in PHP

How to output numbers with two decimal places in PHP

醉折花枝作酒筹
Release: 2023-03-11 18:04:02
forward
2041 people have browsed it

When we need to keep the output data to two decimal places, what should we do? Today I will introduce to you how to format a number with two decimal places in PHP. You can refer to it if you need it.

How to output numbers with two decimal places in PHP

Due to business needs, a number needs to be formatted to two decimal places (rounded):

The first option: round

Code:

$aaa = 15.0393;
var_dump(round($aaa, 2));
$bbb = 16.1;
var_dump(round($bbb, 2));
$ccc = 13;
var_dump(round($ccc, 2));
/**
运行:
double(15.04)
double(16.1)
double(13)
 */
Copy after login

There is a problem with this solution. If the original number has only one decimal or no decimal, it will be output as usual without adding 0 at the end. If rounding up or down, use ceil or floor.

Second solution: number_format

Code:

$aaa = 15.0393;
var_dump(number_format($aaa, 2, '.', ''));

$bbb = 16.1;
var_dump(number_format($bbb, 2, '.', ''));

$ccc = 13;
var_dump(number_format($ccc, 2, '.', ''));

/**
运行:
string(5) "15.04"
string(5) "16.10"
string(5) "13.00"
 */
Copy after login

Although this solution can be filled with 0 at the end, it will be converted into a string.

The third option: sprintf

Code:

$aaa = 15.0393;
var_dump(sprintf('%.2f', $aaa));

$bbb = 16.1;
var_dump(sprintf('%.2f', $bbb));

$ccc = 13;
var_dump(sprintf('%.2f', $ccc));

/**
运行:
string(5) "15.04"
string(5) "16.10"
string(5) "13.00"
 */
Copy after login

is the same as above.

// ToDo: There is no good solution that can add 0 at the end and output a numeric type instead of a string.

Recommended learning: php video tutorial

The above is the detailed content of How to output numbers with two decimal places in PHP. For more information, please follow other related articles on the PHP Chinese website!

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