Inaccurate value when using (int) in PHP

I have a problem with this code block

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

    echo $feeAmount1 . '<br />';

I get this from the result.

27520

I need to convert it to int, but I get the ennacurate value in (int).

Hope someone can help me.

Thanks in advance.

+4
source share
3 answers

It looks like it could be a floating point error.

For example, your FPU may give you an 27520.999...equation 275.21 * 100. (this is close, on the right), and then the decimal places alternate to convert to int.

You can try to round it before converting it to int:

$feeAmount1 = (int) ( round( $Fee * 100) );
+2
source
+2

:

  $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>";

float integer, . .

downvote btw?

float integer .

.     http://php.net/manual/en/language.types.integer.php

, .

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

. float.

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

If your values ​​always come with 2 decimal points, you can use the result without typing in int. Can you provide more details on "Why do you need an integer value?".

Greetings

-1
source

Source: https://habr.com/ru/post/1607609/


All Articles