将数字显示到小数点后两位 [英] Show a number to two decimal places

查看:31
本文介绍了将数字显示到小数点后两位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What's the correct way to round a PHP string to two decimal places?

$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

该函数返回一个字符串.

这篇关于将数字显示到小数点后两位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆