Search code examples
phpstringnumber-formattingtrimmoney-format

Remove specific characters on the right of a string


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!


Solution

  • 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') . "\n";
    echo format_number('£230.12') . "\n";
    echo format_number('£23.024') . "\n";
    echo format_number('£230.00024') . "\n";
    echo format_number('£230.0240') . "\n";
    echo format_number('£230.2') . "\n";
    

    Output:

    £230.00
    £230.12
    £23.024
    £230.00024
    £230.024
    £230.20