1

Is it possible to get float type result from the sum of two integer type variable?

Example:

1 + 2 => 3.0

I have tried using number_format($result, 1) and sprintf("%.1f", $result), but the return value type is string.

Additionally, if I type cast to float then the return value is a float of value 3 and not 3.0

JustCarty
  • 3,839
  • 5
  • 31
  • 51

3 Answers3

3

I suggest you.. you can use sprintf:-

$a = 1+2;
$result = sprintf("%.2f", $a); //3.00  or  $result = sprintf("%.1f", $a); //3.0
echo $result; 

Hope it helps!

kunal
  • 4,122
  • 12
  • 40
  • 75
0

use floatval(); to swith the value to float

check the doc

also please check the similar question PHP - Force integer conversion to float with three decimals

Kareem Essawy
  • 565
  • 1
  • 4
  • 14
0

Your integer variables are in the type int

If you add two int type, the result is inevitably an integer result.

$intOne = 1;
$intTwo = 2;

$result = $intOne + $intTwo; // = (int)3 

You can change the type of your result, easily, but, is not necessary good, if you store an int in your var...

$floatResult = (float) $result; // (float)3

Also, if you don't know the type of your variable you can use the function 'floatval' (official doc here) like that:

$floatOne = floatval('3.14'); // (float)3.14
$floatTwo = floatval("3.141 is a Pi number"); // (float)3.14

In this case, if you add two flaot type, the result is in float two:

$result = $floatOne + floatTwo; // (float)6.281

The best practises want to save the right type on your variable and your database ( read this for more information about types and performance)

if you want just show decimals after your integer type, you can use the number_format() function (official documentation here) like that:

$decimalResult = number_format($floatResult, 4);
echo $decimalResult; // Show '3.0000'        ^ Number of decimals

Hope I help you ;)

Doc Roms
  • 3,288
  • 1
  • 20
  • 37