dongshi8425 2016-01-11 10:45
浏览 65
已采纳

删除字符串右侧的特定字符

I need to remove zeros from the end of a string, but only up to 2 places from the right of a decimal point.

I'got a formatted price being handed over as a string, and that price is up to 5 decimal places. I need to strip unnecessary zeros from the price but leaving at least 2 to the right of a decimal place. For example:

£0.00230 -> £0.0023 and £1.50000 -> £1.50

Any help would be appreciated!

  • 写回答

3条回答 默认 最新

  • dsy19890123 2016-01-11 10:52
    关注

    Final and last update hopefully... trim off all the zeros on the right then add 1 or 2 zeroes if needed.

    function format_number($price) {
        if (preg_match('~^£\d+$~', $price)) {
            $price .= '.00';
        } else {
            $price = rtrim($price, '0');
            if (preg_match('~\.$~', $price)) {
                $price .= '00';
            } elseif (preg_match('~\.\d$~', $price)) {
                $price .= '0';
            }
        }
        return $price;
    }
    echo format_number('£230') . "
    ";
    echo format_number('£230.12') . "
    ";
    echo format_number('£23.024') . "
    ";
    echo format_number('£230.00024') . "
    ";
    echo format_number('£230.0240') . "
    ";
    echo format_number('£230.2') . "
    ";
    

    Output:

    £230.00
    £230.12
    £23.024
    £230.00024
    £230.024
    £230.20
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?