dongshi8425
dongshi8425
2016-01-11 10:45

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

已采纳

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 dsy19890123 5年前

    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
    
    点赞 评论 复制链接分享
  • dongtie0929 dongtie0929 5年前

    You can remove the symbol, cast to float to remove trailing zeros, and use number_format to add them back if needed:

    function fixCurrency($string, $symbol){
    
        //remove £, and any trailing zeros
        $val = (float) ltrim($string, $symbol);
        //add back zeros if needed
        $parts = explode('.', $val);
        if(!isset($parts[1]) || strlen($parts[1]) < 2){
            $val = number_format($val, 2);
        }
        return $symbol . $val;
    
    }
    
    点赞 评论 复制链接分享
  • dongmi1864 dongmi1864 5年前

    Try this code:

    $value = "0.00230";
    $new_value = explode(".", $value);
    $substring = substr($new_value[1], 0, 1);
    
    if($substring == "00"){
      $value = number_format($value, 4, '.', '');
    } else {
      $value = number_format($value, 2, '.', '');
    }
    echo $value;
    
    点赞 评论 复制链接分享