tags:

views:

271

answers:

3

I'm retrieving a float value from a mysql database on a php page (2.5, 3.0 etc)

I would like to format this value so that if it is actually an integer, it should show zero decimal places. (it should output 3 instead of 3.0, but output 2.5 as 2.5)

What would be the simplest way to achieve this?

+3  A: 

I would try something along the lines of:

echo (intval($v) == $v) ? intval($v) : $v;

But I wonder if there's a more efficient way.

Ray Hidayat
that's an assignment error (cannot assign to the result of a function). use this instead: echo (intval($v) == $v) ? intval($v) : $v;
Kris
Don't you mean to use == there?
Sukasa
Also, echo ( $v % 1? $v : intval(%v) ); would reduce your function calls by one, I can't recall the function so I can't say how much faster it might be, then again it might be worse.
Sukasa
Ray I've used your method (but with ==) and it works. Thanks for the help!
Istari
You're welcome Istari! Oops, you're right, == not =. Yeah I thought about that but I couldn't be sure about doing a modulo (%) on a float, so I didn't want to provide that as an answer. If it's valid code that would be my preferred method.
Ray Hidayat
+1  A: 

You could also do the formatting in your query, it is likely to be faster than doing it in php especially if you have many rows to process.

Something like:

SELECT
    CASE 
     WHEN t.myColumn % 1 = 0 
      THEN FORMAT( t.myColumn, 0 ) 
      ELSE FORMAT( t.myColumn, 2 )
    END AS `formatted`
    ...
FROM myTable t
WHERE ...

The same method does apply for php if you want to do it outside the database:

$displayValue = $myValue % 1 == 0 
    ? number_format( $myValue, 0 ) 
    : number_format( $myValue, 2 );
Kris
Interesting to note that it can be done in the DB. In this case it doesn't really matter as I'm looking at one row only. My initial thought was to use the modulus function in PHP but wondered whether there was another way. Thanks for the input
Istari
A: 

You could also use a printf if you want to control the number of digits displayed to the right of the decimal point:

  if (intval($v) == $v) printf("%d", intval($v)); else printf("%0.2f", $v);
PTBNL