Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting int to float/double [duplicate]

Tags:

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".

like image 242
Mike Avatar asked Oct 16 '13 17:10

Mike


1 Answers

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
like image 131
Tamil Selvan C Avatar answered Sep 18 '22 17:09

Tamil Selvan C