1

I have a float number. I want to convert it to a string with the following two rules

  • If the float has no decimal part then do not create any decimal part
  • If the float has a decimal part then convert it to two decimal places

For example

499 => "499"
499.5 => "499.50"
499.99 => "499.99"
499.989 => "499.99"

How would you do that in php?

4

2 に答える 2

3

I think this should do the trick for you:

if(round(($var*100),0)%100==0)
{
    echo round($var,0);
}
else
{
    echo round($var,2);
}

There might be a much more elegant way of doing it, but this will work in the following way:

If the float multiplied by a 100 and rounded ends in 00 (close enough to round to no decimals) then it is echoed without any decimal places. Otherwise it is rounded to two decimal places - the float should take care of rounding too much so I think there will always be two spots visible.

于 2012-09-27T09:27:26.993 に答える
2

You can use number_format with Type Casting (string) in PHP

$numbers = array(499,499.5,499.99,499.989);
foreach ( $numbers as $number ) {
    var_dump(__format($number));
}

Function used

function __format($number) {
    if (is_float($number)) {
        return number_format($number, 2);
    } else {
        return (string) $number;
    }
}

Output

string '499' (length=3)
string '499.50' (length=6)
string '499.99' (length=6)
string '499.99' (length=6)
于 2012-09-27T09:28:24.840 に答える