Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with float multiplication and evaluation

This problem is best expressed in code:

$var1 = 286.46; // user input data
$var2 = 3646; // user input data
$var3 = 25000; // minumum amount allowed
$var4 = ($var1 * 100) - $var2; // = 250000
if ($var4 < $var3) { // if 250000 < 250000
    print 'This returns!';
}

var_dump($var4) outputs: float(25000) and when cast to int, outputs: int(24999) - and thereby lies the problem.

I don't really know what to do about it though. The issue occurs upon multiplication by 100, and while there are little tricks I can do to get around that (such as *10*10) I'd like to know if there's a 'real' solution to this problem.

Thanks :)

like image 474
user1192140 Avatar asked Nov 04 '22 06:11

user1192140


2 Answers

This is a horrible hacky solution and I slightly hate myself for it, but this gives the expected behaviour:

<?php

  $var1 = 286.46; // user input data
  $var2 = 3646; // user input data
  $var3 = 25000; // minumum amount allowed
  $var4 = ($var1 * 100) - $var2; // = 250000
  if ((string) $var4 < (string) $var3) { // if 250000 < 250000
      print 'This returns!';
  }

Cast them to strings, and they get converted back to int/float as appropriate for the comparison. I don't like it but it does work.

Really you need BC Math for precise floating point mathematics in PHP.

like image 104
DaveRandom Avatar answered Nov 07 '22 21:11

DaveRandom


Its always a good idea to use ceil (or floor based on what you want) when using float number as int In your case try ceil($var4) before comparison!

like image 32
rru Avatar answered Nov 07 '22 21:11

rru