Justin
Justin

Reputation: 653

Show decimal point number in PHP

I hold decimals in a database using DECIMAL(10,5)

I would like to format these numbers according to a few rules:

Here are some examples:


0.00000 => 0
0.51231 => 0.51231
0.12000 => 0.12
0.40000 => 0.40
0.67800 => 0.678
12.10000 => 12.10

Upvotes: 0

Views: 1701

Answers (5)

Luke Cousins
Luke Cousins

Reputation: 2156

I know this is an old question, but the following quick function I wrote for my own project might help someone looking for this.

function number_format_least_dp($number, $decimal_point = '.', $thousand_seperator = ','){
    if (floatval($number) == (int)$number){
        $number = number_format($number, 0, $decimal_point, $thousand_seperator);
    } else {
        $number = rtrim($number, '.0');
        $number = number_format($number, strlen(substr(strrchr($number, '.'), 1)), $decimal_point, $thousand_seperator);
    }
    return $number;
}

Upvotes: 0

Godwin
Godwin

Reputation: 9907

Well here's one way (I haven't tested it yet so there may be minor errors):

$pattern = '/([0-9]+)\\.{0,1}([0-9]*?)0*$/';
$subject = 12.10000;
$matches = array();
$result = preg_match ($pattern, $subject, $matches);
$number = $matches[1];
if ($matches[2] != 0) {
    $number .= '.'.$matches[2];
    if ($matches[2] < 10) {
        $number .= '0';
    }
}
echo $number;

And here's another way (probably a little faster):

$x = 1.000;
$result = (int)$x;

$trimmed = rtrim($x, 0);
if ($trimmed[strlen($trimmed) - 1] != '.') {
    if ($trimmed[strlen($trimmed) - 2] == '.') {
        $result = $trimmed.'0';
    } else {
        $result = $trimmed;
    }
}
echo $result;

Upvotes: 1

Paul
Paul

Reputation: 141839

This will work for you:

function format($x){
    if(!(int)substr_replace($x, '', $dpos = strpos($x, '.'), 1))
        return 0;
    else
        return str_pad((rtrim($x, '0')), $dpos + 3, '0'); 
}

Example

Upvotes: 2

DanMan
DanMan

Reputation: 11561

I haven't used it myself, but theres the NumberFormatter class: http://php.net/manual/class.numberformatter.php as part of the Internationalization Functions for this stuff. Using that is a little more involved i think though.

Upvotes: 0

CHawk
CHawk

Reputation: 1356

I would utilize the number_format function in php to actually do the formatting after you determine the amount of decimal places to the number has.

Source: http://php.net/manual/en/function.number-format.php

Example Usage:

$number = 1234.56;

// english notation (default)
$english_format_number = number_format($number);
// 1,235

// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56

$number = 1234.5678;

// english notation without thousands separator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57

Upvotes: 1

Related Questions