douyasihefu6214 2019-07-25 05:48
浏览 384
已采纳

PHP:始终在EXCEL中显示小数位,甚至是零

I am generating an excel sheet using Content-Type: application/vnd.ms-excel. Code looks like this

    $filename = "Stack_Rank_ReportV2_(".$fromdate."_".$todate.").xls";
        header("Pragma: no-cache");
        header("Content-Type: application/vnd.ms-excel");    
        header("Content-Disposition: attachment; filename=$filename");      
        header("Expires: 0");

        $head_row  = "Emp. ID"."\t";
        $head_row .= "Employee Name"."
";
        echo $head_row;

        $user_row = $users[$userid]['empid']."\t";
        $user_row .= $users[$userid]['name']."
";
        echo $user_row;

The problem is that the decimal points are ignored by excel if it is zero say 1.000 becomes 1 but shows properly if it is 1.001. I'm looking for something like setFormatCode() that is there in PHPEXCEL. Is there a way to acheive this?

  • 写回答

1条回答 默认 最新

  • douwen0612 2019-07-25 06:05
    关注

    You can do it, but it will have to be a string instead of a float.

    $nums = [1, 10.00, 10.001, 1.000, 0];
    
    function f($num){
        if(!strpos($num, '.')) $num = number_format($num, 2, '.', '');
        return $num;
    }
    
    foreach ($nums as $num) echo f($num)."
    ";
    

    Output:

    1.00
    10.00
    10.001
    1.00
    0.00
    

    Sandbox

    You can't see it but the types are diffrent

    string(4) "1.00"
    string(5) "10.00"
    float(10.001)
    string(4) "1.00"
    string(4) "0.00"
    

    Not really a "big deal" for PHP but something to be aware of. PHP won't display a float with the zeros. Once it converts to string the 0's are removed, which is why strpos above works when the number version has the .. I should add when you do echo or otherwise output a float with 0's PHP will convert it to a string and remove them, so you have to convert it yourself using number format etc...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用