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 numbers that have a fractional part. In the computer world, numbers that carry a fractional part 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.

When testing this in the Groovy’s environment, I only ran the test cases with the Groovy’s built-in mathematical calculation function. Nevertheless, the code of this article was run against 100,000+ test cases. In regard to imprecise floating point calculation, when you are working within the Groovy 2.4.4’s environment and apply this mathematical equation of 1677245.8 + -7214.597. Groovy will give you the answer of 1670031.1. Nonetheless, if we were to calculate the answer manually, we know that the correct answer is 1670031.203. 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 Groovy’s built-in float calculation. For each answer, the one of the left is Groovy’s answer, and the one on the right is the answer provided by the script at the end of this article.

Question: 1677245.8 + -7214.597 Groovy Answer: 1670031.1 | infiA: 1670031.203 Question: 702128.5 + -3636.4233 Groovy Answer: 698492.06 | infiA: 698492.0767 Question: 3372601.5 + -506.1441 Groovy Answer: 3372095.2 | infiA: 3372095.3559 Question: 962907.5 + -8977.101 Groovy Answer: 953930.4 | infiA: 953930.399 Question: 7115456.5 + -2787.855 Groovy Answer: 7112668.5 | infiA: 7112668.645

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

When storing numbers with a fractional part 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 fractional part 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 a fractional part 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 does contain a fractional part. 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. In Groovy, we can get the first character in a string using the charAt() string prototype function. The charAt() function takes an integer value for input, that value is then used as a position to grab a character from the defined position within the string. For Groovy’s strings, the zero position is the first position in a 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.

int isaNeg = a.charAt(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 Groovy’s string prototype built in function replaceAll() with a regex pattern to search for and remove any positive and negative sign at the beginning 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 = a.replaceAll('^[+-]+', "") a = a.replaceAll('^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. We can just simply check the first position of the string to see whether if the position does contain a decimal using a regex pattern as a matching condition. I’m using a regex conditional statement here instead of the charAt() function is because I just want to demonstrate an alternative method that can produce the same result for the same procedure.

a = (a.matches('^[.]{1}\\d{0,}'))? "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 Groovy’s string prototype function replaceAll() with a regex pattern that can evaluate and remove all 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 code line below, 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 ( a.matches('\\d{0,}[.]{1}\\d{0,}') ){ adec = a.replaceAll('^[0-9]{0,}[.]', "") a = a.replaceAll('[.][0-9]{0,}$', "") }

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.

int adeclen = adec.length() int bdeclen = bdec.length() 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)? Integer.parseInt(String.valueOf(adec.charAt(i)), 10) : 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 = String.valueOf(temp).concat(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 = ".".concat(output) output = output.replaceAll('[0]{1,}$', "") output = output.replaceAll('[.]$', "")

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 = String.valueOf(temp).concat(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 temporary 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 = String.valueOf(temp).concat(output)

The code is below is the full function of this tutorial. it’s possible to add plenty more than 500 digits together.

**Advertisement**

// "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. public class libZ { public static String infiA (String a, String b) { int isaNeg = a.charAt(0) == '-'? 1 : 0 int isbNeg = b.charAt(0) == '-'? 1 : 0 a = a.replaceAll('^[+-]+', "") b = b.replaceAll('^[+-]+', "") a = a.replaceAll('^0+', "") b = b.replaceAll('^0+', "") a = a.matches('^[.]{1}\\d{0,}')? "0".concat(a) : a b = b.matches('^[.]{1}\\d{0,}')? "0".concat(b) : b String adec = "" String bdec = "" if (a.indexOf(".") > -1){ adec = a.replaceAll('^[0-9]{0,}[.]', "") a = a.replaceAll('[.][0-9]{0,}$', "") } if (b.indexOf(".") > -1){ bdec = b.replaceAll('^[0-9]{0,}[.]', "") b = b.replaceAll('[.][0-9]{0,}$', "") } int aidx = a.length() - 1 int bidx = b.length() - 1 int adeclen = adec.length() int bdeclen = bdec.length() int carryOver = 0 int temp = 0 int x = 0 int y = 0 String output = "" if (isaNeg == isbNeg){ if (adeclen > 0 || bdeclen > 0){ int i = (adeclen > bdeclen)? adeclen - 1 : bdeclen - 1 while (i > -1){ x = (i < adeclen)? Integer.parseInt(String.valueOf(adec.charAt(i)), 10) : 0 y = (i < bdeclen)? Integer.parseInt(String.valueOf(bdec.charAt(i)), 10) : 0 temp = x + y + carryOver carryOver = (temp > 9)? 1 : 0 temp = temp > 9? temp - 10 : temp output = String.valueOf(temp).concat(output) i-- } output = ".".concat(output) output = output.replaceAll('[0]{1,}$', "") output = output.replaceAll('[.]$', "") } while (aidx > -1 || bidx > -1){ x = aidx > -1? Integer.parseInt(String.valueOf(a.charAt(aidx)), 10) : 0 y = bidx > -1? Integer.parseInt(String.valueOf(b.charAt(bidx)), 10) : 0 temp = x + y + carryOver carryOver = temp > 9? 1 : 0 temp = temp > 9? temp - 10 : temp output = String.valueOf(temp).concat(output) output = aidx < 1 && bidx < 1? String.valueOf(carryOver).concat(output): output aidx = aidx - 1 bidx = bidx - 1 } output = output.replaceAll('^0+', "") output = (output.matches('^[.]{1}\\d{0,}') || output.length() < 1)? "0".concat(output) : output return isaNeg == 1 && isbNeg == 1? "-".concat(output) : output } else if (isaNeg != isbNeg){ String larger = a.length() > b.length()? "a" : (b.length() > a.length()? "b" : "1") if (larger.equals("1")){ larger = "" for (int i = 0; i < a.length() ; i++){ larger = Integer.parseInt(String.valueOf(a.charAt(i)), 10) > Integer.parseInt(String.valueOf(b.charAt(i)), 10)? "a" : larger larger = Integer.parseInt(String.valueOf(b.charAt(i)), 10) > Integer.parseInt(String.valueOf(a.charAt(i)), 10)? "b": larger i = larger.length() > 0? a.length() : i larger = i == a.length() - 1 && larger.length() < 1? "0" : larger } if ((adeclen > 0 || bdeclen > 0 ) && larger == "0"){ int max = (adeclen > bdeclen)? adeclen : bdeclen for (int i = 0; i < max ; i++){ x = (i < adeclen)? Integer.parseInt(String.valueOf(adec.charAt(i)), 10) : 0 y = (i < bdeclen)? Integer.parseInt(String.valueOf(bdec.charAt(i)), 10) : 0 larger = (x > y)? "a": (y > x? "b" : "0" ) i = (larger.equals("a") || larger.equals("b"))? max : i } } } if (larger.equals("0")){ return larger } else if (larger.equals("a")){ if (adeclen > 0 || bdeclen > 0){ int i = (adeclen > bdeclen)? adeclen - 1 : bdeclen - 1 while (i > -1){ x = (i < adeclen)? Integer.parseInt(String.valueOf(adec.charAt(i)), 10) : 0 y = (i < bdeclen)? Integer.parseInt(String.valueOf(bdec.charAt(i)), 10) : 0 temp = x - y - carryOver carryOver = temp < 0? 1 : 0 temp = temp < 0? 10 + temp : temp output = String.valueOf(temp).concat(output) i-- } output = ".".concat(output) output = output.replaceAll('[0]{1,}$', "") output = output.replaceAll('[.]$', "") } while (aidx > -1){ x = Integer.parseInt(String.valueOf(a.charAt(aidx)), 10) y = bidx > -1? Integer.parseInt(String.valueOf(b.charAt(bidx)), 10) : 0 temp = x - y - carryOver carryOver = temp < 0? 1 : 0 temp = temp < 0? 10 + temp : temp output = String.valueOf(temp).concat(output) aidx = aidx - 1 bidx = bidx - 1 } output = output.replaceAll('^0+', "") output = (output.matches('^[.]{1}\\d{0,}'))? "0".concat(output) : output return isaNeg == 1? "-".concat(output) : output } else if (larger.equals("b")){ if (adeclen > 0 || bdeclen > 0){ int i = (adeclen > bdeclen)? adeclen - 1 : bdeclen - 1 while (i > -1){ x = (i < adeclen)? Integer.parseInt(String.valueOf(adec.charAt(i)), 10) : 0 y = (i < bdeclen)? Integer.parseInt(String.valueOf(bdec.charAt(i)), 10) : 0 temp = x - y + carryOver carryOver = temp > 0? 1 : 0 temp = temp > 0? 10 - temp : temp - temp - temp output = String.valueOf(temp).concat(output) i-- } output = ".".concat(output) output = output.replaceAll('[0]{1,}$', "") output = output.replaceAll('[.]\$', "") } while (bidx > -1){ x = aidx > -1? Integer.parseInt(String.valueOf(a.charAt(aidx)), 10) : 0 y = Integer.parseInt(String.valueOf(b.charAt(bidx)), 10) temp = x - y + carryOver carryOver = temp > 0? 1 : 0 temp = temp > 0? 10 - temp : temp - temp - temp output = String.valueOf(temp).concat(output) aidx = aidx - 1 bidx = bidx - 1 } output = output.replaceAll('^0+', "") output = (output.matches('^[.]{1}\\d{0,}'))? "0".concat(output) : output return isaNeg == 0? "-".concat(output) : output } } return output } } String c = "999999999999999999999999999.99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999" String d = "999999999999999999999999999.99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999" println(libZ.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 – Groovy".

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

**Advertisement**