1

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?

Community
  • 1
  • 1

4 Answers4

3

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 = ',' )
Jean-Philippe Bond
  • 10,089
  • 3
  • 34
  • 60
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.

jordanm
  • 33,009
  • 7
  • 61
  • 76
2

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.

Fabian Schmengler
  • 24,155
  • 9
  • 79
  • 111
  • it has a float type but it is hidden. In the most naural level of php you use scalar type, but at a lower level you do use true types. An evidence is in the functions `is_int`for example which answers `false`when you say `is_int("14")`. You can also use cast operators. so Jean-Philippe Bond has the right answer. – artragis Jan 20 '13 at 19:38
  • @artragis you are missing my point. I said, PHP has no *fixed point* data type (like decimal(10,2) in MySQL). Of course it has floats and I don't see how that would be hidden. – Fabian Schmengler Jan 20 '13 at 19:40
  • oh yes you are right misread you. – artragis Jan 20 '13 at 19:40
1

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);
hohner
  • 11,498
  • 8
  • 49
  • 84