Possible Duplicate:
PHP: show a number to 2 decimal places
$b = $del['Antal'];
$y = $info['Pris'];
$z = $y * $b;
$y comes from a mysql database where its type is "double(10,2)" so that one works when I try echo $y; it responds with two decimals.
But now I would like to multiply it with $b.
For example 10.20 * 2 = 20.40
But right now it is like: 10.20 * 2 = 20.4 (only one decimal)
I want two decimals, what to do? I tried some stuff with the (double) function, but didn't really work out. What to do?
You can use number_format :
$b = $del['Antal'];
$y = $info['Pris'];
$z = number_format($y * $b ,2);
The number_format
function :
string number_format ( float $number [, int $decimals = 0 ] )
And if you don't want the default format :
string number_format ( float $number , int $decimals = 0 , string $dec_point = '.' , string $thousands_sep = ',' )
Try floatval
:
$z = $y * floatval($b);
Alternatively:
$b = (float) $b;
It should automatically convert to a float, however, if you multiply it by 10.20. Read PHP's documentation on type juggling.
If it's merely a styling thing:
$b = number_format($b, 2);
You can ensure that you store it at two decimal places by using sprintf and storing it as a string:
$z = sprintf('%.2f', $y * $b);
The %.2f
ensure that there are always two digits after the decimal point.
The data type you describe are fixed point numbers, not floating point numbers (float). PHP does not have such a data type, however it can format
floats for you. And it seems like that is what you are looking for, formatting output.