24

I am running into troubles when I want to convert integer values to float (numbers with dots).

$a = 7200;
$b = $a/3600;

echo $b; // 2

$b = floatval($b);

echo $b; // 2

But it should echo 2.0 or 2.00

I also tried settype, without success. And I am finding only help/solutions/questions for "float to int".

Mike
  • 3,200
  • 5
  • 22
  • 33
  • 2 and 2.0 are the same number float or not. I understand that you are not seeing the decimal as you like, but the math you are doing is coming up with an int for a quotient. Do you experience the same when dividing by floating point numbers? – Crackertastic Oct 16 '13 at 17:15

4 Answers4

38

Updated:

Use

echo sprintf("%.2f", $b); // returns 2.00

Use

echo number_format($b, 2);

eg:

echo number_format(1234, 2); // returns 1,234.00

Edit:

@DavidBaucum Yes, number_format() returns string.

Use

echo sprintf("%.2f", $b);

For your question, use

Why number_format doesn't work can be demonstrated by this. echo number_format(1234,0) + 1.0 The result is 2

echo sprintf("%.2f",(1234 + 1.0 ) ); // returns 1235.00
Tamil Selvan C
  • 19,913
  • 12
  • 49
  • 70
11

You can use number_format() function to accomplish this. This function also allows you to define the number of zeroes to be displayed after the decimal -- you just need to use the second parameter for that:

$a = 7200;
$b = $a/3600;
$b = floatval($b);
echo number_format($b, 2, '.', '');

Or, if you want to do it one line:

echo number_format( (float) $b, 2, '.', '');

Output:

2.00

Demo!

Amal Murali
  • 75,622
  • 18
  • 128
  • 150
9

Something like:

<?php
    $a = 7200;
    $b = $a/3600;

    $b = number_format($b,2);

    echo $b; // 2.00
?>

-

number_format(number,decimals,decimalpoint,separator)
Blazer
  • 14,259
  • 3
  • 30
  • 53
3

I found a solution by myself:

    $b = number_format((float)$b, 1, '.', '');
echo $b; // 2.0

does the trick

Mike
  • 3,200
  • 5
  • 22
  • 33