php - 显示一个数字到小数点后两位

标签 php formatting numbers rounding number-formatting

将 PHP 字符串四舍五入到小数点后两位的正确方法是什么?

$number = "520"; // It's a string from a database

$formatted_number = round_to_2dp($number);

echo $formatted_number;

输出应该是520.00;

round_to_2dp()函数定义应该如何?

最佳答案

您可以使用 number_format() :

return number_format((float)$number, 2, '.', '');

例子:

$foo = "105";
echo number_format((float)$foo, 2, '.', '');  // Outputs -> 105.00

这个函数返回一个字符串

关于php - 显示一个数字到小数点后两位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4483540/

相关文章:

Excel 单元格格式特殊情况

java - 为什么我的 Java 代码无法运行?

algorithm - 求解线性丢番图方程的算法是什么: ax + by = c

php - Laravel 不遵守相关模型更新的质量分配 $fillable 规则

matlab - 显示来自 MATLAB 的信息而无需换行

css - 无法使用 class=pull-right 或 float :right 向右浮动 twitter Bootstrap 导航栏元素

Haskell -- 如何将数字拆分为列表以进行进一步处理?

php - 消息: Undefined index: when getting column name (two table with the same column) CodeIgniter

php - mysql数据库多对多关系困惑

php - Where 和 If 语句 Laravel Eloquent