I'm using a Money class that requires all currency to be in int
in order to instantiate it. What's happened is I've run across a specific number (I've tried with a variety of other numbers and everything works as expected) that when type cast from float
to int
, has a different value.
I might expect this from a very high precision number due to the nature of floating point numbers in general, but this is not making any sense, here's how I can reproduce the error...
$value = (float)9.78;
var_dump($value );
$prec = (int)(100);
var_dump($prec);
$value = $value * $prec;
var_dump($value);
var_dump((int)($value));
... which produces the following output ...
float(9.78) /* $value as a float */
int(100) /* $prec as an int */
float(978) /* $value * $prec as a float, all going well... */
int(977) /* $value type cast to an int ???????? */
... what the hell is going on here? Why is $value
type cast to an int
in this scenario coming up with a different value?
EDIT: The reason I'm not accepting this as a duplicate is due to the answer I needed not being present in the other thread. Here it is: I had to apply round()
like so...
$dec_precision = strlen((string)($prec)-1);
$value = round($value * $prec, $dec_precision);
Hope that helps someone!