0

Please note that I am not looking to round floating point numbers, I am trying to establish a maximum precision to prevent rounding errors. E.g.

1/3 + 1/3 + 1/3 = 1
// when I would round to two decimals that would result in the loss of a cent
0.33 + 0.33 + 0.33 = 0.99
// that is why I want to check a maximum precision on input

If you can make this function work as expected it will probably be a good answer:

$a = 1.003;
$b = 1.02;
$c = 3;

function test_input( float $floatingNumber ): string {
  if() // What should I check for?
   echo 'Okay, this number has 2 or less digits';
  else
   echo 'string has too many digits';
}

test_input( $a ); // should echo 'string has too many digits'
test_input( $b ); // should echo 'Okay, this number has 2 or less digits';
test_input( $c ); // should echo 'Okay, this number has 2 or less digits';

Note: Using the modulus operator did cross my mind, but the modulus operator can only be used on integers.

Note2: I think recursing over the floating point number removing 0.01 a time until 0 is left or something between 0 and 0.01 would work. But that seems to be an inelegant and inefficient way to approach this.

Note3: I could cast the floating point to a string, then check with a regExp, then cast it back to a floating point. But I would prefer to check on the floating point number itself.

Rob Monhemius
  • 4,822
  • 2
  • 17
  • 49

1 Answers1

0

Use strlen(substr(strrchr($a, "."), 1)

function test_input( float $floatingNumber ) {
   if( strlen( substr( strrchr( $floatingNumber, "." ), 1 ) ) )
     echo 'Okay, this number has 2 or less digits';
   else
     echo 'string has too many digits';
}
Rob Monhemius
  • 4,822
  • 2
  • 17
  • 49
Osama
  • 2,912
  • 1
  • 12
  • 15
  • This is basically casting to a string and checking the length of the RegExp. It should work, but checking floats as if they are strings feels a bit off to me; That is probably just me being a bit weird about these things tough ;). – Rob Monhemius Apr 28 '19 at 00:38