4

I am having a problem on this block of code

    $Fee = 275.21;
    $feeAmount1 = (int) ( floatval ( $Fee ) * 100 );

    echo $feeAmount1 . '<br />';

I'm getting an this on te result.

27520

I need to convert it to int but I'm getting ennacurate value in (int) function.

Hope someone can help me with this.

Thanks is advance.

Eddie
  • 26,593
  • 6
  • 36
  • 58

3 Answers3

2

Sounds like it could be a floating point error.

For example your FPU might give you 27520.999... for the equation 275.21 * 100. (it's close, right) and then the decimals are striped on the conversion to an int.

You could try rounding it before converting it to an int:

$feeAmount1 = (int) ( round( $Fee * 100) );
complistic
  • 2,610
  • 1
  • 29
  • 37
2

It is a known behaviour of php.

A float, like 27521, is in fact something like 27520.999999999999991. When you cast it, you truncate the decimal part.

So use round, floor or ceil methods to round it to the closest integer :

http://php.net/manual/en/function.round.php

http://php.net/manual/en/function.ceil.php

http://php.net/manual/en/function.floor.php

Damien_FR
  • 53
  • 5
-1

Change your code to this :

  $Fee = 275.21;
  echo $FeeWOD = round($Fee * 100); //Should be 27521,00
  echo "<br>";
  echo $feeAmount1 = (float) $FeeWOD;
  echo "<br>";
  echo intval ($feeAmount1);
  echo "<br>";

It will not work from float to integer as this page says. You need rounding first.

Why is the downvote btw?

When converting from float to integer, the number will be rounded towards zero.

Read this page. http://php.net/manual/en/language.types.integer.php

Warning

Never cast an unknown fraction to integer, as this can sometimes lead to unexpected results.

<?php
   echo (int) ( (0.1+0.7) * 10 ); // echoes 7!
?>

See also the warning about float precision.

http://php.net/manual/en/language.types.float.php#warn.float-precision

If your values are always coming with 2 decimal points you can use the result without type casting it into int. Can you provide more details on "Why do you need an integer value?" .

Cheers

CntkCtn
  • 357
  • 2
  • 7