0

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++; } */ 

2 Answers 2

1

Get the number of digits after the decimal. Then create a number with a decimal point, one less 0, followed by 1, to get the amount to add.

$valueOne = 12.345678; // get amount of decimals $decimal = strlen(strrchr($valueOne, '.')) -1; // see value before change echo $valueOne . "<br>\n"; // Get amount to add $increment = '.' . str_repeat('0', $decimal-1) . '1'; $valueOne += $increment; echo $valueOne; 
Sign up to request clarification or add additional context in comments.

2 Comments

@Barmer Thanks for your help! How would I adjust the code if there was a 0 at the end of the decimal, for example if the number is 12.3450, the code ignores the 0 and outputs 12.346. How I can get it to output 12.3451?
You have to write the number as a string: "12.3450". Otherwise the PHP parser ignores trailing zeroes, there's no way to tell that it was originally written that way.
1

Get the number of decimals

Multiply by the appropriate factor so the number is now an integer

Increment by 1

Divide by the same factor to get back to the original number (properly incremented)

function increment($number){ // get amount of decimals $decimal = strlen(strrchr($valueOne, '.')) -1; $factor = pow(10,$decimal); $incremented = (($factor * $number) + 1) / $factor; return $incremented; } 

1 Comment

$valueOne is not defined,maybe you have $number in mind

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.