Chris Muench
Chris Muench

Reputation: 18318

showing between 2-4 decimal places (php)

I am trying to figure out a way to produce the following output:

4.0000 = 4.00

4.5000 = 4.50

4.454= 4.454

4.54545454 = 4.5455

4.450 = 4.45

Basically I want to make sure there is ALWAYS at least 2 decimal places and if there are extra zeros, trim to 2 decimal places. If there is more than 4 decimal places round and keep at 4.

I can use:

number_format($number, 4, '.', '');

then rtrim to remove zeros, but this will leave me with less than 2 decimal places in many cases.

Upvotes: 1

Views: 1277

Answers (3)

mcrumley
mcrumley

Reputation: 5700

function format_number($number) {
    $str = number_format($number, 4, '.', '');
    return preg_replace('/(?<=\d{2})0+$/', '', $str);
}

format_number(4.0)        // "4.00"
format_number(4.5)        // "4.50"
format_number(4.454)      // "4.454"
format_number(4.54545454) // "4.5455"
format_number(4.450)      // "4.45"

Upvotes: 4

MonkeyZeus
MonkeyZeus

Reputation: 20737

I would do something like this if you are looking to avoid REGEX:

$arr = array();
$arr = 4.0000;
$arr = 4.5000;
$arr = 4.454;
$arr = 4.54545454;
$arr = 4.450;

foreach($arr as $k=>$v)
{
    $arr[$k] = number_format($v, 4, '.', '');

    $vals = exlode('.', (string)$arr[$k]);

    if(substr($vals[1], -1, 1) === '0')
    {
        $arr[$k] = (float)$vals[0].'.'.substr($vals[1], -1, 1);

        $vals = exlode('.', (string)$arr[$k]);

        if(substr($vals[1], -1, 1) === '0')
        {
            $arr[$k] = (float)$vals[0].'.'.substr($vals[1], -1, 1);
        }
    }
}

Upvotes: 0

Pitchinnate
Pitchinnate

Reputation: 7556

Here is one way you could do it:

function myround($input) {
    $floor = floor($input);
    $remain = rtrim($input- $floor);
    if(strlen($remain) > 4) {
        return number_format($floor + $remain,4);
    } else {
        return number_format($floor + $remain,2);
    }
}

print_r(myround(4.312423)); //outputs 4.3124
print_r(myround(4.3)); //outputs 4.30
print_r(myround(4)); //outputs 4.00

Upvotes: 1

Related Questions