duanquannan0593 2011-03-25 08:03
浏览 36
已采纳

PHP仅显示重要(非零)小数

In PHP (using built-in functions) I'd like to convert/format a number with decimal, so that only the non-zero decimals show. However, another requirement of mine is that if it's a number without a decimal value, I'd still like to show that zero. Examples:

9.000 -> 9.0
9.100 -> 9.1
9.120 -> 9.12
9.123 -> 9.123

rtrim($value, "0") almost works. The problem with rtrim is that it leaves 9.000 as 9.. sprintf() seemed like a candidate, but I couldn't get it to have a variable amount of decimals. number_format() serves a different purpose, and those were all I could come up with...

Again, I'd like to point out that I am not looking for your homemade solutions to this, I'm looking for a way to accomplish this using internal PHP functionality. I can write a function that will accomplish this easily myself, so hold answers like that.

  • 写回答

11条回答 默认 最新

  • dongxiao_0528 2011-03-25 08:06
    关注

    I don't think theres a way to do that. A regex is probably your best solution:

    $value = preg_replace('/(\.[0-9]+?)0*$/', '$1', $value);
    

    Demo:

    php> $a = array('0.000', '0.0001', '0.0101', '9.000', '9.100', '9.120', '9.123');
    php> foreach($a as $b) { echo $b . ' => ' . preg_replace('/(\.[0-9]+?)0*$/', '$1', $b)."
    "; }
    0.000 => 0.0
    0.0001 => 0.0001
    0.0101 => 0.0101
    9.000 => 9.0
    9.100 => 9.1
    9.120 => 9.12
    9.123 => 9.123
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(10条)

报告相同问题?

悬赏问题

  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动