I am trying to slightly increment a value based on the number of decimals it has.
For example if the value is 1.2 I would increase it by 0.1, 12.345 by 0.001, 12.345678 by 0.000001, etc.
I currently have a long implementation using a chain of if, else if. I know this is not the most efficient way and a loop can be used, but I was unsure of how to structure the loop. I tried using the PHP substr_replace function, but I could not get it to work for this.
Is there another way I can structure a loop to reduce my lines of code and be more efficient?
Here is my php code so far:
$valueOne = 12.345678; // get amount of decimals $decimal = strlen(strrchr($valueOne, '.')) -1; /* this also works for finding how many decimals $test = floatval($valueOne); for ( $decimal_count = 0; $test != round($test, $decimal_count); $decimal_count++ ); echo $decimal_count; */ // see value before change echo $valueOne; if ($decimal == "1") { $valueOne = $valueOne + 0.1; } else if ($decimal == "2") { $valueOne = $valueOne + 0.01; } else if ($decimal == "3") { $valueOne = $valueOne + 0.001; } // etc ... // see value after change echo $valueOne; /* i tried messing around with using a loop, but did not have much luck $start = 0.1; $count = 0; $position = 2; while ($count != $decimal) { echo substr_replace($start, 0, $position, 0) . "<br />\n"; $count++; //$position++; } */