douzhuan1169 2013-11-25 20:20
浏览 97
已采纳

显示2-4个小数位(php)

I am trying to figure out a way to produce the following output:

4.0000 = 4.00

4.5000 = 4.50

4.454= 4.454

4.54545454 = 4.5455

4.450 = 4.45

Basically I want to make sure there is ALWAYS at least 2 decimal places and if there are extra zeros, trim to 2 decimal places. If there is more than 4 decimal places round and keep at 4.

I can use:

number_format($number, 4, '.', '');

then rtrim to remove zeros, but this will leave me with less than 2 decimal places in many cases.

  • 写回答

3条回答 默认 最新

  • dtzjvj3915 2013-11-25 20:38
    关注
    function format_number($number) {
        $str = number_format($number, 4, '.', '');
        return preg_replace('/(?<=\d{2})0+$/', '', $str);
    }
    
    format_number(4.0)        // "4.00"
    format_number(4.5)        // "4.50"
    format_number(4.454)      // "4.454"
    format_number(4.54545454) // "4.5455"
    format_number(4.450)      // "4.45"
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了