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.