The previous chapter of Infinity Adding was discussing in regard to storing two integer numbers in string format and how to apply a mathematical addition equation on the two strings of digits by adding one digit at a time to produce an answer.

When we are discussing in regard to a mathematical calculation, one of the important components is how to deal with decimal values. In the computer world, numbers that carry decimal values are often called float or floating point values. When calculating a floating point value, a majority of computer’s program will not calculate the precise value. Computer’s program will often round a floating point value to get a near precise calculation. Sometimes even on basic mathematical equations that only involved addition, the computer can’t generate a precise floating point calculation.

For example, when you are working within the PHP five point six’s environment and apply this mathematical equation of -35261.520213 + 35458.309077. PHP will give you the answer of 196.78886399999. Nevertheless, if we calculate the answer manually, we know that the correct answer is 196.788864. This type of method is the computer’s standard basic method for calculating values with a decimal placement. However, what happened if we truly need a precise decimal point value to be calculated without rounding the answer, and the numbers that involve in the equation have the possibility to have more than five hundred digits behind the decimal? This is chapter two of Infinity Adding, “Decimal, Precise Float Calculation”.

Note: The source code of chapter one and two of the Infinity Addition subject are prototypes. The prototypes purposes are to demonstrate the procedures for adding large numbers together. They are not meant for a production environment due to efficiency issue. Chapter three will have a production version of the source code.

This is a sample log of the result I got from executing the script that attaches to this article compare to PHP’s built-in float calculation. For each answer, the one of the left is PHP’s answer, and the one on the right is the answer provided by the script at the end of this article.

Question: -38676.724605 + 38674.721002 PHP Answer: -2.0036030000047 | My Answer: -2.003603 Question: -82827.592204 + 83723.490142 PHP Answer: 895.89793799999 | My Answer: 895.897938 Question: -56246.680051 + 55780.405724 PHP Answer: -466.27432700001 | My Answer: -466.274327 Question: -89936.689918 + 89665.209156 PHP Answer: -271.48076200001 | My Answer: -271.480762 Question: -52649.562228 + 52713.860197 PHP Answer: 64.297968999999 | My Answer: 64.297969

### How To Add Two Floating Numbers Together In String Format

When storing numbers with decimal values in string format, the first challenge we would have when we are applying a mathematical equation on the string is the digits behind the decimal. The string of number can be split into an array, where one index of the array holds the digits before the decimal and the other index holds the digits behind the decimal. Nevertheless, there is a high possibility that the amount of digit behind the decimal that each string has can vary. That can be solved by padding zeroes on the right of the shorter string to make both strings of number contain the exact same amount of digits behind the decimal.

Besides array, we can also split one string with the decimal value into two strings. After the split, one string can carry the digits before the decimal, and the other string can carry the digits behind the decimal. Thus if we were going to add two strings of numbers that contain decimal values together, we can have up to four strings. An example of this would be if we were to add A and B together where both A and B contain decimal values. Then we would split A into two. Where A1 can contain the digits before the decimal and A2 contains the digits behind the decimal. The same scenario would also apply to B1 and B2.

When it comes to calculating the digits behind the decimal, we can pad zeroes to the right of B2 if B2 is shorter than A2 to produce the equivalent amount of digits behind the decimal or vice-versa if A2 is shorter than B2. Another method to this would be, instead of padding zeroes, we can read the longer string first from the right. As long as the position we read is not less than or equal to the largest position of the shorter string, we would not read from the shorter string, instead, we would assign a value of zero in lieu of the shorter string’s digit. The addition formula for calculating the digits behind the decimal would be the same as calculating the digits before the decimal. We only have one additional procedure when it comes to adding values that are behind the decimal, and it is the final carry-over value from the equation have to be carried over to the equation of adding the two strings of digits that are before the decimal.

In this chapter, the majority of the information is in regard to the source code and explanations of the programming procedures for the source code.

Let first start with evaluating the input value of the string. First I use a conditional statement to test if the string is positive or negative in value by looking at the first character in the string. If the first character in the string is a negative sign, the variable isaNeg will be assigned with the value of one, of which can also be equal to a boolean value of true. For anything else, we assign a zero value to isaNeg. To get a character by position in PHP, we could use the string_variable_name[<position>] option. Which can grab a character from the inputted position in a string, with the zero position being the first position in the string.

Note that you can also use a boolean declaration here with a true or false value. Nevertheless, I used a digit value here for isaNeg in the prototype to demonstrates another method for evaluating and storing a true or false value.

$isaNeg = $a[0] == "-"? 1 : 0;

After evaluating whether if the string can be a negative value or not, I removed any plus or minus sign using the ltrim() function of PHP. The ltrim() function will trim both the minus and the plus sign from the left side of the string. We would also want to remove leading zeroes. This is because leading zeroes before the decimal do not offer any additional value to the number.

$a = ltrim($a, "+-"); $a = ltrim($a, "0");

We would then need to initialize a third evaluation on the input. If the user input .123 without putting a zero in front of the decimal then we have to append a single zero to the front of the decimal. Therefore, we would evaluate whether if the first character of the string is a decimal. If it is a decimal, we add a zero to the string. If the first character is not a decimal, the string will be itself. For this situation, we can use the preg_match() function in PHP to search for and remove the decimal point using a regex pattern as a matching condition. I’m using a regex condition evaluation check here to check and not the “[]” option is because I just want to demonstrate an alternative method that can produce the same result for the same procedure.

$a = (preg_match("/^[.]{1}/", $a))? "0" . $a : $a;

After the above evaluation, I then evaluate if the string does contain a decimal by using regex. If the string does contain a decimal, I will use the preg_replace() function with a regex pattern that can evaluate and remove all the digits that are before the decimal, including the decimal from A string. The leftover digits are then assigned to a variable name adec. Variable adec is now holding the digits that are behind the decimal. Since I did the previous procedure through a variable assignment statement, the value of string A has not changed. On the third line of code, I removed all the digits that are behind the decimal and including the decimal in the value of variable A. Variable A is now holding all the digits that are before the decimal.

if (preg_match( '/[.]/', $a) ){ $adec = preg_replace("/^[0-9]{0,}[.]/", "" , $a); $a = preg_replace("/[.][0-9]{0,}$/", "", $a); }

When it comes to the strings that contain the digits behind the decimal, in the event where they do not contain a value, it would be very inefficiency to add the empty strings together. Also, the digits behind the decimal have to be added together first before the digits before the decimal. To be able to execute the equation efficiently, we would have to wrap our code block for adding the digits behind the decimal right before the code block for adding the digits before the decimal. On the first two lines of the below code, adeclen and bdeclen are the lengths of the strings that contain the digits behind the decimal. The if statement code block will only execute if either one of the lengths of the strings that contain the digits behind the decimal is higher than zero. In others word, either adec or bdec need to have a length for the code block to execute.

$adeclen = strlen($adec); $bdeclen = strlen($bdec); if ($adeclen > 0 || $bdeclen > 0){ // Equation code goes here }

While reading through the strings in a while loop or in a for loop, let assume the $i variable is the index count and we will use it as the read position value to get a digit from our strings. We would only read the string that contains the digits behind the decimal if the current position value in the $i variable is lower than the string’s maximum length. If the read position is within the string length, we would get a digit from that string at that position. Then we would convert the digit that we just obtained to an integer format. For anything else, we assign a value of zero in lieu of the string’s value.

$x = ($i < $adeclen)? intval($adec[$i] : 0;

When calculating the carry-over value for the next equation, we simply evaluate if the temporary answer’s value is higher than nine. If the temporary result value is higher than nine then we would assign one to the carry-over value. In a mathematical addition equation that only involves two sets of digits then the carry-over value can never be larger than the value of one. In the temporary result value, for anything else that is below the value of nine, we would assign a zero value to the carry-over value.

When assigning a value to the output, it is a constant that we will always assign the rightmost digit from the temporary answer to the left of the output string. We can base our evaluations on two conditions to get the rightmost digit from the temporary answer. If the result value is higher than nine, we take a value of ten and subtract to the temporary result value. For anything else, we simply keep the result value. This method can only be applied to a mathematical addition equation. Also, we can only apply this method when adding only two sets of digits together. This is because the carry-over value can never be larger than a value of one.

$temp = $x + $y + $carryOver; $carryOver = $temp > 9? 1 : 0; $temp = $temp > 9? $temp - 10 : $temp; $output = strval($temp) . $output;

After adding the entire two strings of digits behind the decimal together and the output string contained the full result value for the equation. We would then need to append a decimal point to the front of the output string before going into our next calculation. We then check for any zeroes to the right of the output string and remove all ending zeroes. As opposed to a whole number, trailing zeroes to the right side of the digits that are behind a decimal point do not provide any additional value. After removing all the zeroes, if the last character is only the decimal then we would also remove the decimal. The previous two procedures are done through regex on line two and three.

$output = "." . $output; $output = preg_replace("/[0]{1,}$/", "", $output); $output = preg_replace("/[.]$/" , "", $output);

The above explanations are important code lines for adding a positive number to a positive number. Let discuss some important code lines for adding a positive number to a negative number. Or a negative number to a positive number. The principles for adding a positive value to a negative value can be described as subtracting the two values. The result value from this type of equation will carry the same negative or positive base as the larger value.

The example below is for the event of when the first string of input being the higher value string. In the first code line, we are subtracting the first string’s digit to the second string’s digit then to any carry-over value. For the second code line, we are assigning a carry-over value bases on a condition. If the result value is less than zero then we assign a value of one to the carry-over value. Otherwise, a value of zero is assigned to the carry-over value. This is easy to achieve when we are only dealing with two sets of digits. If we were dealing with more than two sets of digits then we would have to implement another method.

On the third code line, if the result value is less than zero, or in others word, a negative value. Then we would take a value of ten and add to the result value. Otherwise, we would not alter the result value. We then place the result value to the left of the output string, the code statement for this is on the fourth code line.

$temp = $x - $y - $carryOver; $carryOver = $temp < 0? 1 : 0; $temp = $temp < 0? 10 + $temp : $temp; $output = strval($temp) . $output;

The above is if the first input string is higher in value. When it’s come to the second input string that is higher in value, the equation’s procedures do not change, nevertheless, there are differences between the two equation. When comparing the first line of code to the above equation’s procedure, we are still subtracting the first string’s digit to the second string’s digit. Nonetheless, instead of subtracting to the carry-over value, we are now adding to the carry-over value. The main change in how we are assigning the carry-over value is the temporary result value has to be larger than zero for us to assign a value of one to the carry-over value.

On the third code line below, the ending is very important. The temporary result value that does not need to be modified is now negative in value. If we are going to convert a negative integer value to a string type format and then placing the value to the output string, we would have a minus sign between every digit. Thus we can either subtract the temporary result value to itself twice to reach its positive value, convert the temporary result value to a string type and grab the rightmost digit, or simply, multiply the result value to a negative value of one.

$temp = $x - $y + $carryOver; $carryOver = $temp > 0? 1 : 0; $temp = $temp > 0? 10 - $temp : ($temp - $temp - $temp); $output = strval($temp) . $output;

The code is below is the full function of this tutorial.

**Advertisement**

<?php // "Copyright Notice", please do not remove. // Written by Kevin Ng // The full tutorial on this subject can be found @ http://kevinhng86.iblog.website or http://programming.world.edu. // Release date to http://programming.world.edu will lag one week after release on http://kevinhng86.iblog.website // This source code file is a part of Kevin Ng's Z library. // This source code is licenses under CCDL-1.0 A copy of CDDL1.0 can be found at https://opensource.org/licenses/CDDL-1.0 // End "Copyright Notice" // Notice: This is version 2 of infiA from Kevin Ng's LibZ library. // This is not a production version and is a prototype. // This version has been tested, but would be too slow in a production environment. // This version of infiA support mathematical addition with the decimal. function infiA($a,$b){ $isaNeg = $a[0] == "-"? 1 : 0; $isbNeg = $b[0] == "-"? 1 : 0; $a = ltrim($a, "+-"); $b = ltrim($b, "+-"); $a = ltrim($a, "0"); $b = ltrim($b, "0"); $a = (preg_match("/^[.]{1}/", $a))? "0" . $a : $a; $b = (preg_match("/^[.]{1}/", $b))? "0" . $b : $b; $adec = ""; $bdec = ""; if (preg_match( '/[.]/', $a)){ $adec = preg_replace("/^[0-9]{0,}[.]/", "", $a); $a = preg_replace("/[.][0-9]{0,}$/", "", $a); } if (preg_match( '/[.]/', $b)){ $bdec = preg_replace("/^[0-9]{0,}[.]/", "", $b); $b = preg_replace("/[.][0-9]{0,}$/", "", $b); } $aidx = strlen($a) - 1; $bidx = strlen($b) - 1; $adeclen = strlen($adec); $bdeclen = strlen($bdec); $x = 0; $y = 0; $carryOver = 0; $temp = 0; $output = ""; if ($isaNeg == $isbNeg){ if ($adeclen > 0 || $bdeclen > 0){ $i = ($adeclen > $bdeclen)? $adeclen - 1 : $bdeclen - 1; while ($i > -1){ $x = ($i < $adeclen)? intval($adec[$i]) : 0; $y = ($i < $bdeclen)? intval($bdec[$i]) : 0; $temp = $x + $y + $carryOver; $carryOver = $temp > 9? 1 : 0; $temp = $temp > 9? $temp - 10 : $temp; $output = strval($temp) . $output; $i--; } $output = "." . $output; $output = preg_replace("/[0]{1,}$/", "", $output); $output = preg_replace("/[.]$/" , "", $output); } while ($aidx > -1 || $bidx > -1){ $x = $aidx > -1? intval($a[$aidx]) : 0; $y = $bidx > -1? intval($b[$bidx]) : 0; $temp = $x + $y + $carryOver; $carryOver = $temp > 9? 1 : 0; $temp = $temp > 9? $temp - 10 : $temp; $output = strval($temp) . $output; $output = $aidx < 1 && $bidx < 1? strval($carryOver) . $output: $output ; $aidx = $aidx - 1; $bidx = $bidx - 1; } $output = ltrim($output, "0") ; $output = (preg_match("/^[.]{1}/", $output) || strlen($output) < 1)? "0" . $output : $output; return $isaNeg == 1 && $isbNeg == 1? "-" . $output : $output; } else if ($isaNeg != $isbNeg){ $larger = strlen($a) > strlen($b) ? "a" : (strlen($b) > strlen($a)? "b" : "1"); if ($larger == "1"){ $larger = ""; for ($i = 0; $i < strlen($a) ; $i++){ $larger = intval($a[$i]) > intval($b[$i])? "a" : $larger; $larger = intval($b[$i]) > intval($a[$i])? "b" : $larger; $i = strlen($larger) > 0? $i = strlen($a) : $i; $larger = $i == strlen($a) - 1 && strlen($larger) < 1? "0" : $larger; } if (($adec != "" || $bdec != "") && $larger == "0"){ $max = ($adeclen > $bdeclen)? $adeclen : $bdeclen; for ($i = 0; $i < $max ; $i++){ $x = ($i < $adeclen)? intval($adec[$i]) : 0; $y = ($i < $bdeclen)? intval($bdec[$i]) : 0; $larger = ($x > $y)? "a": ($y > $x? "b" : "0"); $i = ($larger == "a" || $larger == "b")? $max : $i; } } } if ($larger == "0"){ return $larger; } if ($larger == "a"){ if ($adeclen > 0 || $bdeclen > 0){ $i = ($adeclen > $bdeclen)? $adeclen - 1 : $bdeclen - 1 ; while ($i > -1){ $x = ($i < $adeclen)? intval($adec[$i]) : 0; $y = ($i < $bdeclen)? intval($bdec[$i]) : 0; $temp = $x - $y - $carryOver; $carryOver = $temp < 0? 1 : 0; $temp = $temp < 0? 10 + $temp : $temp; $output = strval($temp) . $output; $i--; } $output = "." . $output; $output = preg_replace("/[0]{1,}$/", "", $output); $output = preg_replace("/[.]$/" , "", $output); } while ($aidx > -1){ $x = intval($a[$aidx]); $y = $bidx > -1? intval($b[$bidx]) : 0; $temp = $x - $y - $carryOver; $carryOver = $temp < 0? 1 : 0; $temp = $temp < 0? 10 + $temp : $temp; $output = strval($temp) . $output; $aidx = $aidx - 1; $bidx = $bidx - 1; } $output = ltrim($output, "0") ; $output = preg_match("/^[.]{1}/", $output)? "0" . $output : $output; return $isaNeg == 1? "-" . $output : $output; } else if ($larger == "b"){ if ($adeclen > 0 || $bdeclen > 0){ $i = ($adeclen > $bdeclen)? $adeclen - 1 : $bdeclen - 1; while ($i > -1){ $x = ($i < $adeclen)? intval($adec[$i]) : 0; $y = ($i < $bdeclen)? intval($bdec[$i]) : 0; $temp = $x - $y + $carryOver; $carryOver = $temp > 0? 1 : 0; $temp = $temp > 0? 10 - $temp : ($temp - $temp - $temp); $output = strval($temp) . $output; $i--; } $output = "." . $output; $output = preg_replace("/[0]{1,}$/", "", $output); $output = preg_replace("/[.]$/" , "", $output); } while ($bidx > -1){ $x = $aidx > -1? intval($a[$aidx]) : 0; $y = intval($b[$bidx]); $temp = $x - $y + $carryOver; $carryOver = $temp > 0? 1 : 0; $temp = $temp > 0? 10 - $temp : ($temp - $temp - $temp); $output = strval($temp) . $output; $aidx = $aidx - 1; $bidx = $bidx - 1; } $output = ltrim($output, "0") ; $output = preg_match("/^[.]{1}/", $output)? "0" . $output : $output; return $isaNeg == 0? "-" . $output : $output; } } } // Test case $c = "999999999999999999999999999999999999.9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999"; $d = "999999999999999999999999999999999999.9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999"; echo infiA($c, $d); ?>

This post was written by Kevin and was first post @ http://kevinhng86.iblog.website.

Original Post Name: "Working With Number – Infinity Adding – Decimal, Precise Float Calculation – PHP".

Original Post Link: http://kevinhng86.iblog.website/2017/02/06/working-with-number-infinity-adding-decimal-precise-float-calculation-php/.

**Advertisement**