duanfei8149 2016-10-07 16:45
浏览 229
已采纳

仅显示一个小数位或不显示浮点数

I'm aware of number_format(..) that behaves like following:

number_format(2.5, 1) // returns 2.5
number_format(2.0, 1) // returns 2.0 <-- needs to be just 2

The problem is, that I don't want .0 to be shown at all. How to format the float correctly to achieve this?

  • 写回答

2条回答 默认 最新

  • duanlachu7344 2016-10-07 16:51
    关注

    One option is to use round instead of number_format:

    echo round(2.0, 1); // 2
    echo round(2.5, 1); // 2.5
    echo round(2.555555, 1); // 2.6
    echo round(2.501, 1); // 2.5
    echo round(2.1050, 1); // 2.1
    

    Another option is to cast your number to a float after using number_format, which will eliminate any trailing zeros after the decimal point.

    echo (float) number_format(2.0, 1); // 2
    echo (float) number_format(2.5, 1); // 2.5
    echo (float) number_format(2.555555, 1); // 2.6
    echo (float) number_format(2.501, 1); // 2.5
    echo (float) number_format(2.1050, 1); // 2.1
    

    Both will give you a maximum of a single decimal place. I think round is the better option here.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R
  • ¥15 在线请求openmv与pixhawk 实现实时目标跟踪的具体通讯方法
  • ¥15 八路抢答器设计出现故障
  • ¥15 opencv 无法读取视频
  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档