Skip to content
Related Articles
Open in App
Not now

Related Articles

Sum of two large Floating-point numbers

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 15 Sep, 2022
Improve Article
Save Article

Given two very large floating-point numbers in form of large strings str1 and str2, the task is to add the given two numbers. Example:

Input: str1 = “584506134.87368350839565308”, str2 = “30598657.0330473560587475634983” Output: 615104791.9067308644544006434983 Input: str1 = “38.30”, str2 = “37.0983” Output: 75.3983

Approach: To find the addition of two large integers that can’t be stored in the inbuilt data type we will use an array to store the digits of the numbers and then perform the addition digit by digit starting from the LSB. Using this concept, we can also find the summation of large floating-point numbers. Steps to add the two given floating-point numbers:

  1. Split both the given floating-point number in form of a string with respect to the decimal point to separate the fractional and integer part of the numbers.
  2. Add the fractional and integer part of the two numbers separately and forward the final carry part of fractional addition to integers part. For Example:
str1 = "23.94" and str2 = "34.23"

For fractional part:
f1[] = {4, 9}
f2[] = {3, 2}
--------------
Sum  = {7, 1, 1}
Therefore, Carry = 1

For Integer part:
Carry = 1
I1[] = {3, 2}
I2[] = {4, 3}
--------------
Sum  = {8, 5}
  1. Concatenate the digits stored for integer and fractional part with a decimal ‘.’ to get the required sum two large floating point numbers.
From Integer part = 58
From fractional part = 17

Sum = 58.17

Below is the implementation of the above approach: 

CPP




// C++ program to find Sum of two
// large Floating-point numbers
   
#include <bits/stdc++.h>
using namespace std;
   
// Function to make fractional part
// with equal digits
void makeEqualAtFront(vector<int>& A,
                      vector<int>& B)
{
    int n = A.size();
    int m = B.size();
    int diff = abs(n - m);
   
    if (n < m) {
        for (int i = 0; i < diff; i++) {
            A.insert(A.begin(), 0);
        }
    }
    else {
        for (int i = 0; i < diff; i++) {
            B.insert(B.begin(), 0);
        }
    }
}
   
// Function to make Integral part
// with equal digits
void makeEqualAtback(vector<int>& A,
                     vector<int>& B)
{
    int n = A.size();
    int m = B.size();
    int diff = abs(n - m);
   
    if (n < m) {
        for (int i = 0; i < diff; i++) {
            A.push_back(0);
        }
    }
    else {
        for (int i = 0; i < diff; i++) {
            B.push_back(0);
        }
    }
}
   
// Function to add the given large
// floating point number string
void findSum(string s1, string s2)
{
   
    int i;
   
    // To store the integer and
    // fractional part of numbers
    vector<int> Ints1, Ints2;
    vector<int> Fracs1, Fracs2;
   
    // Separating integer and
    // fractional part of s1
    for (i = s1.length() - 1; i > -1; i--) {
   
        // If decimal occurs break
        if (s1[i] == '.') {
            break;
        }
        Fracs1.push_back(s1[i] - '0');
    }
   
    i--;
    for (; i > -1; i--) {
        Ints1.push_back(s1[i] - '0');
    }
   
    // Separating integer and
    // fractional part of s2
    for (i = s2.length() - 1; i > -1; i--) {
   
        // If decimal occurs break
        if (s2[i] == '.') {
            break;
        }
        Fracs2.push_back(s2[i] - '0');
    }
   
    i--;
    for (; i > -1; i--) {
        Ints2.push_back(s2[i] - '0');
    }
   
    // Making number of digits in
    // fractional and Integer
    // part equal
    makeEqualAtFront(Fracs1, Fracs2);
    makeEqualAtback(Ints1, Ints2);
   
    // Adding fractional parts of
    // s1 and s2
    int n = Fracs1.size();
    int m = Fracs2.size();
    i = 0;
    int carry = 0;
   
    while (i < n && i < m) {
   
        // Traverse the Fracs1[] and
        // Fracs2[] and add the digit
        // and store the carry
        int sum = Fracs1[i]
                  + Fracs2[i]
                  + carry;
   
        Fracs1[i] = sum % 10;
        carry = sum / 10;
        i++;
    }
   
    int N = Ints1.size();
    int M = Ints2.size();
    i = 0;
   
    // Adding integer part of
    // s1 and s2
    while (i < N && i < M) {
        int sum = Ints1[i]
                  + Ints2[i]
                  + carry;
        Ints1[i] = sum % 10;
        carry = sum / 10;
        i++;
    }
    if (carry != 0)
        Ints1.push_back(carry);
   
    // Print the result by appending
    // Integer and decimal part stored
    // in Ints1[] and Fracs1[]
    for (int i = Ints1.size() - 1; i > -1; i--) {
        cout << Ints1[i];
    }
    cout << '.';
    for (int i = Fracs1.size() - 1; i > -1; i--) {
        cout << Fracs1[i];
    }
}
   
// Driver Code
int main()
{
    string str1
        = "584506134.87368350839565308";
    string str2
        = "30598657.0330473560587475634983";
   
    findSum(str1, str2);
   
    return 0;
}

Java




// Java program to find Sum of two
// large Floating-point numbers
import java.util.*;
 
@SuppressWarnings("unchecked")
class GFG
{
 
  // Function to make fractional part
  // with equal digits
  static ArrayList<Integer>[] makeEqualAtFront(ArrayList<Integer> A,
                                      ArrayList<Integer> B)
  {
    int n = A.size();
    int m = B.size();
    int diff = Math.abs(n - m);
 
    if (n < m) {
      for (var i = 0; i < diff; i++) {
        A.add(0, 0);
      }
    }
    else {
      for (var i = 0; i < diff; i++) {
        B.add(0, 0);
      }
    }
     
     ArrayList<Integer>[] l1 = new ArrayList[2];
    l1[0] = A;
    l1[1] = B;
    return l1;
  }
 
  // Function to make Integral part
  // with equal digits
  static ArrayList<Integer>[] makeEqualAtback(ArrayList<Integer> A,
                                     ArrayList<Integer> B)
  {
    int n = A.size();
    int m = B.size();
    int diff = Math.abs(n - m);
 
    if (n < m) {
      for (var i = 0; i < diff; i++) {
        A.add(0);
      }
    }
    else {
      for (var i = 0; i < diff; i++) {
        B.add(0);
      }
    }
 
    ArrayList<Integer>[] l1 = new ArrayList[2];
    l1[0] = A;
    l1[1] = B;
    return l1;
  }
 
  // Function to add the given large
  // floating point number string
  static void findSum(String s1, String s2)
  {
 
    int i;
 
    // To store the integer and
    // fractional part of numbers
    ArrayList<Integer> Ints1 = new ArrayList<Integer>();
    ArrayList<Integer> Ints2 = new ArrayList<Integer>();
    ArrayList<Integer> Fracs1 = new ArrayList<Integer>();
    ArrayList<Integer> Fracs2 = new ArrayList<Integer>();
 
    // Separating integer and
    // fractional part of s1
    for (i = s1.length() - 1; i > -1; i--) {
 
      // If decimal occurs break
      if (s1.charAt(i) == '.') {
        break;
      }
      Fracs1.add(s1.charAt(i) - '0');
    }
 
    i--;
    for (; i > -1; i--) {
      Ints1.add(s1.charAt(i) - '0');
    }
 
    // Separating integer and
    // fractional part of s2
    for (i = s2.length() - 1; i > -1; i--) {
 
      // If decimal occurs break
      if (s2.charAt(i) == '.') {
        break;
      }
      Fracs2.add(s2.charAt(i) - '0');
    }
 
    i--;
    for (; i > -1; i--) {
      Ints2.add(s2.charAt(i) - '0');
    }
 
    // Making number of digits in
    // fractional and Integer
    // part equal
    ArrayList<Integer>[] res1 = makeEqualAtFront(Fracs1, Fracs2);
    ArrayList<Integer>[] res2 = makeEqualAtback(Ints1, Ints2);
    Fracs1 = res1[0];
    Fracs2 = res1[1];
    Ints1 = res2[0];
    Ints2 = res2[1];
 
    // Adding fractional parts of
    // s1 and s2
    int n = Fracs1.size();
    int m = Fracs2.size();
    i = 0;
    int carry = 0;
 
    while (i < n && i < m) {
 
      // Traverse the Fracs1[] and
      // Fracs2[] and add the digit
      // and store the carry
      int sum = Fracs1.get(i) + Fracs2.get(i) + carry;
 
      Fracs1.set(i, sum % 10);
      carry = (sum >= 10) ? 1 : 0;
      i++;
    }
 
    int N = Ints1.size();
    int M = Ints2.size();
    i = 0;
 
    // Adding integer part of
    // s1 and s2
    while (i < N && i < M) {
      int sum = Ints1.get(i) + Ints2.get(i) + carry;
      Ints1.set(i, sum % 10);
      carry = (sum >= 10) ? 1 : 0;
      i++;
    }
 
    if (carry != 0)
      Ints1.add(carry);
 
    // Print the result by appending
    // Integer and decimal part stored
    Collections.reverse(Ints1);
    Collections.reverse(Fracs1);
 
    for (int i1 : Ints1) System.out.print(i1);
    System.out.print(".");
    for (int i1 : Fracs1) System.out.print(i1);
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    String str1 = "584506134.87368350839565308";
    String str2 = "30598657.0330473560587475634983";
 
    findSum(str1, str2);
  }
}
 
// This code is contributed by phasing17.

Python3




# Python3 program to find Sum of two
# large Floating-point numbers
   
# Function to make fractional part
# with equal digits
def makeEqualAtFront(A, B):
 
    n = len(A)
    m = len(B)
    diff = abs(n - m);
   
    if (n < m) :
        for i in range(diff):
            A.insert(0, 0)
    else :
        for i in range(diff):
            B.insert(0, 0)
 
     
    return (A, B)
 
   
# Function to make Integral part
# with equal digits
def makeEqualAtback(A, B):
    n = len(A)
    m = len(B)
    diff = abs(n - m);
   
    if (n < m) :
        for i in range(diff):
            A.append(0)
    else :
        for i in range(diff):
            B.append(0)
             
    return (A, B)
     
   
# Function to add the given large
# floating point number string
def findSum(s1, s2):
   
    # To store the integer and
    # fractional part of numbers
    Ints1 = []
    Ints2 = [];
    Fracs1 = []
    Fracs2 = [];
   
    # Separating integer and
    # fractional part of s1
    i = len(s1) - 1
    while i > -1:
 
        # If decimal occurs break
        if (s1[i] == '.') :
            break;
         
        Fracs1.append(int(s1[i]));
        i -= 1
     
   
    i -= 1
    while i > -1:
        Ints1.append(int(s1[i]));
        i -= 1
     
   
    # Separating integer and
    # fractional part of s2
    i = len(s2) - 1
    while i > -1:
 
        # If decimal occurs break
        if (s2[i] == '.') :
            break;
         
        Fracs2.append(int(s2[i]));
        i -= 1
     
   
    i -= 1
    while i > -1:
        Ints2.append(int(s2[i]));
        i -= 1
     
   
    # Making number of digits in
    # fractional and Integer
    # part equal
    Fracs1, Fracs2 = makeEqualAtFront(Fracs1, Fracs2);
    Ints1, Ints2 = makeEqualAtback(Ints1, Ints2);
   
    # Adding fractional parts of
    # s1 and s2
    n = len(Fracs1)
    m = len(Fracs2);
    i = 0;
    carry = 0;
  
    while (i < n and i < m):
   
        # Traverse the Fracs1[] and
        # Fracs2[] and add the digit
        # and store the carry
        sums = Fracs1[i] + Fracs2[i] + carry;
   
        Fracs1[i] = sums % 10;
        carry = int(sums / 10);
         
        i += 1
     
    N = len(Ints1);
    M = len(Ints2);
    i = 0;
   
    # Adding integer part of
    # s1 and s2
    while (i < N and i < M):
        sums = Ints1[i] + Ints2[i] + carry;
        Ints1[i] = sums % 10;
        carry = int(sums / 10);
        i += 1
     
    if (carry != 0):
        Ints1.append(carry);
   
    # Print the result by appending
    # Integer and decimal part stored
    Ints1 = Ints1[::-1]
    Fracs1 = Fracs1[::-1]
    print(*Ints1, ".", *Fracs1, sep = "")
 
# Driver Code
str1  = "584506134.87368350839565308";
str2  = "30598657.0330473560587475634983";
   
findSum(str1, str2);
 
 
# This code is contributed by phasing17.

C#




// C# program to find Sum of two
// large Floating-point numbers
using System;
using System.Collections.Generic;
 
class GFG
{
 
  // Function to make fractional part
  // with equal digits
  static List<int>[] makeEqualAtFront(List<int> A,
                                      List<int> B)
  {
    int n = A.Count;
    int m = B.Count;
    int diff = Math.Abs(n - m);
 
    if (n < m) {
      for (var i = 0; i < diff; i++) {
        A.Insert(0, 0);
      }
    }
    else {
      for (var i = 0; i < diff; i++) {
        B.Insert(0, 0);
      }
    }
 
    return new[] { A, B };
  }
 
  // Function to make Integral part
  // with equal digits
  static List<int>[] makeEqualAtback(List<int> A,
                                     List<int> B)
  {
    int n = A.Count;
    int m = B.Count;
    int diff = Math.Abs(n - m);
 
    if (n < m) {
      for (var i = 0; i < diff; i++) {
        A.Add(0);
      }
    }
    else {
      for (var i = 0; i < diff; i++) {
        B.Add(0);
      }
    }
 
    return new[] { A, B };
  }
 
  // Function to add the given large
  // floating point number string
  static void findSum(string s1, string s2)
  {
 
    int i;
 
    // To store the integer and
    // fractional part of numbers
    List<int> Ints1 = new List<int>();
    List<int> Ints2 = new List<int>();
    List<int> Fracs1 = new List<int>();
    List<int> Fracs2 = new List<int>();
 
    // Separating integer and
    // fractional part of s1
    for (i = s1.Length - 1; i > -1; i--) {
 
      // If decimal occurs break
      if (s1[i] == '.') {
        break;
      }
      Fracs1.Add(s1[i] - '0');
    }
 
    i--;
    for (; i > -1; i--) {
      Ints1.Add(s1[i] - '0');
    }
 
    // Separating integer and
    // fractional part of s2
    for (i = s2.Length - 1; i > -1; i--) {
 
      // If decimal occurs break
      if (s2[i] == '.') {
        break;
      }
      Fracs2.Add(s2[i] - '0');
    }
 
    i--;
    for (; i > -1; i--) {
      Ints2.Add(s2[i] - '0');
    }
 
    // Making number of digits in
    // fractional and Integer
    // part equal
    List<int>[] res1 = makeEqualAtFront(Fracs1, Fracs2);
    List<int>[] res2 = makeEqualAtback(Ints1, Ints2);
    Fracs1 = res1[0];
    Fracs2 = res1[1];
    Ints1 = res2[0];
    Ints2 = res2[1];
 
    // Adding fractional parts of
    // s1 and s2
    int n = Fracs1.Count;
    int m = Fracs2.Count;
    i = 0;
    int carry = 0;
 
    while (i < n && i < m) {
 
      // Traverse the Fracs1[] and
      // Fracs2[] and add the digit
      // and store the carry
      int sum = Fracs1[i] + Fracs2[i] + carry;
 
      Fracs1[i] = sum % 10;
      carry = (sum >= 10) ? 1 : 0;
      i++;
    }
 
    int N = Ints1.Count;
    int M = Ints2.Count;
    i = 0;
 
    // Adding integer part of
    // s1 and s2
    while (i < N && i < M) {
      int sum = Ints1[i] + Ints2[i] + carry;
      Ints1[i] = sum % 10;
      carry = (sum >= 10) ? 1 : 0;
      i++;
    }
 
    if (carry != 0)
      Ints1.Add(carry);
 
    // Print the result by appending
    // Integer and decimal part stored
    Ints1.Reverse();
    Fracs1.Reverse();
 
    foreach(int i1 in Ints1) Console.Write(i1);
    Console.Write(".");
    foreach(int i1 in Fracs1) Console.Write(i1);
  }
 
  // Driver Code
  public static void Main(string[] args)
  {
    string str1 = "584506134.87368350839565308";
    string str2 = "30598657.0330473560587475634983";
 
    findSum(str1, str2);
  }
}
 
// This code is contributed by phasing17.

Javascript




// JS program to find Sum of two
// large Floating-point numbers
   
   
// Function to make fractional part
// with equal digits
function makeEqualAtFront(A, B)
{
    let n = A.length;
    let m = B.length;
    let diff = Math.abs(n - m);
   
    if (n < m) {
        for (var i = 0; i < diff; i++) {
            A.unshift(0);
        }
    }
    else {
        for (var i = 0; i < diff; i++) {
            B.unshift(0);
        }
    }
     
    return [A, B]
}
   
// Function to make Integral part
// with equal digits
function makeEqualAtback(A, B)
{
     
    let n = A.length;
    let m = B.length;
    let diff = Math.abs(n - m);
   
    if (n < m) {
        for (var i = 0; i < diff; i++) {
            A.push(0);
        }
    }
    else {
        for (var i = 0; i < diff; i++) {
            B.push(0);
        }
    }
    return [A, B]
}
   
// Function to add the given large
// floating point number string
function findSum(s1, s2)
{
   
    let i;
   
    // To store the integer and
    // fractional part of numbers
   let Ints1 = [], Ints2 = [];
let Fracs1 = [], Fracs2 = [];
   
    // Separating integer and
    // fractional part of s1
    for (i = s1.length - 1; i > -1; i--) {
   
        // If decimal occurs break
        if (s1[i] == '.') {
            break;
        }
        Fracs1.push(parseInt(s1[i]));
    }
   
    i--;
    for (; i > -1; i--) {
        Ints1.push(parseInt(s1[i]));
    }
   
    // Separating integer and
    // fractional part of s2
    for (i = s2.length - 1; i > -1; i--) {
   
        // If decimal occurs break
        if (s2[i] == '.') {
            break;
        }
        Fracs2.push(parseInt(s2[i]));
    }
   
    i--;
    for (; i > -1; i--) {
        Ints2.push(parseInt(s2[i]));
    }
   
    // Making number of digits in
    // fractional and Integer
    // part equal
    let res1 = makeEqualAtFront(Fracs1, Fracs2);
    let res2 = makeEqualAtback(Ints1, Ints2);
    Fracs1 = res1[0]
    Fracs2 = res1[1]
    Ints1 = res2[0]
    Ints2 = res2[1]
   
    // Adding fractional parts of
    // s1 and s2
    let n = Fracs1.length
    let m = Fracs2.length;
    i = 0;
    let carry = 0;
  
    while (i < n && i < m) {
   
        // Traverse the Fracs1[] and
        // Fracs2[] and add the digit
        // and store the carry
        let sum = Fracs1[i]
                  + Fracs2[i]
                  + carry;
   
        Fracs1[i] = sum % 10;
        carry = Math.floor(sum / 10);
        i++;
    }
   
    let N = Ints1.length;
    let M = Ints2.length;
    i = 0;
   
    // Adding integer part of
    // s1 and s2
    while (i < N && i < M) {
        let sum = Ints1[i]
                  + Ints2[i]
                  + carry;
        Ints1[i] = sum % 10;
        carry = Math.floor(sum / 10);
        i++;
    }
    if (carry != 0)
        Ints1.push(carry);
   
    // Print the result by appending
    // Integer and decimal part stored
    Ints1.reverse()
    Fracs1.reverse()
    console.log(Ints1.join("") + "." + Fracs1.join(""))
}
   
// Driver Code
let str1
        = "584506134.87368350839565308";
let str2
        = "30598657.0330473560587475634983";
   
    findSum(str1, str2);
 
// This code is contributed by phasing17.

Output:

615104791.9067308644544006434983

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!