3

Number format adds the commas I want but removes the decimals.

echo number_format("1000000.25");

This returns 1,000,000

I want it to return 1,000,000.25

I need both the commas and the decimals, without any number rounding. All my values are decimals. They vary in length.

Do I have to use something other than number format?

Cody Raspien
  • 1,753
  • 5
  • 26
  • 51

3 Answers3

10

In case what you meant by they vary in length is related to the decimal part, take a look at this code:

function getLen($var){
    $tmp = explode('.', $var);
    if(count($tmp)>1){
        return strlen($tmp[1]);
    }
}
$var = '1000000.255555'; // '1000000.25'; // '1000000';
echo number_format($var, getLen($var));


Some tests
  • Output for 1000000.255555:

1,000,000.255555


Output for 1000000.25:

1,000,000.25


Output for 1000000:

1,000,000


It counts how many chars there are after the . and uses that as argument in the number_format function;

Otherwise just use a constant number instead of the function call.


And some reference...

From the manual -> number_format():

string number_format ( float $number [, int $decimals = 0 ] )

And you can see in the description that

number
The number being formatted.

decimals
Sets the number of decimal points.

And a bit more:

[...]If two parameters are given, number will be formatted with decimals decimals with a dot (".") in front, and a comma (",") between every group of thousands.

FirstOne
  • 6,033
  • 7
  • 26
  • 45
  • You should return 0 as an else option for your getLen function: function getLen($var){ $tmp = explode('.', $var); if(count($tmp)>1){ return strlen($tmp[1]); }else{ return 0;} } – NVG Oct 24 '22 at 11:52
10
$number = '1000000.25';
echo number_format($number, strlen(substr(strrchr($number, "."), 1)));

Explanation: Number Format takes a second parameter which specifies the number of decimal places required as pointed out in the docs. This Stack overflow answer tells you how to get the number of decimal places of your provided string

Community
  • 1
  • 1
ExoticChimp
  • 1,884
  • 1
  • 19
  • 37
3

The docs for number_format() indicate the second parameter is used to specify decimal:

echo number_format('1000000.25', 2);

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

Nathan
  • 1,700
  • 12
  • 15