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

醉折花枝作酒筹
醉折花枝作酒筹forward
2021-07-21 17:47:442122browse

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)
 */

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"
 */

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"
 */

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!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete