Open In App

Program to convert float decimal to Octal number

Last Updated : 11 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Write a program that converts a floating-point decimal number into its octal format. The program should take a number and the precision for the octal fractional part as inputs from the user. It should calculate and provide its correct octal representation as output.

Examples:

Input: Number = 123.45, No. of decimal places (Precision): 5
Output: 173.34631

Input: 7.1234, No. of decimal places (Precision): 7
Output: 7.0771344

Approach: To solve the problem follow the below idea:

To convert a float decimal number into an octal number, first you should focus on separating the integer and decimal parts. Then, convert the integer part by repeatedly dividing it by 8. Now, start converting the decimal part by multiplying it by 8 and extracting the digits. Finally, combine both the calculations to get your correct octal representation.

Let us dry-run a simple example to understand this conversion in a better way:

Consider a float number: 123.45

  • At first, separate the integer and decimal parts.
  • For the integer part:
    • The integer part of 123 in base 10 is directly converted to base 8 for octal
    • 123 (base 10) = 173 (base 8)
  • For the fractional part:
    • First iteration: 0.45*8 = 3.6. Hence, the first octal digit is ‘3’.
    • Second iteration: 0.6* 8 = 4.8. The second digit is ‘4’.
  • Combine these two calculations:
    • 123.45 (base 10) = 173.34 (base 8) …(approximate value).

Steps to solve the problem:

  • Initialize two input variables: number and its precision value to be considered for output.
  • As discussed in the approach above, convert the integer part first.
  • Create an empty string ‘str’. Loop until the integer part is greater than 0.
  • Calculate the remainder and convert it to string. Then, add it to the beginning of ‘str.
  • Now, for the decimal part, create an empty string with a “.” at the start.
  • Multiply the fractional part by 8, extract the integer part and append it to the string.
  • Update the ‘num’ to be the remaining fractional part.
  • At the end, concatenate both the strings ‘s1’ and ‘s2’ to obtain the answer.

Below is the Code for the above approach:

C++




// C++ code for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to convert the integer part
string convertInteger(int num)
{
    // Initialize an empty string
    string str = "";
    // Loop until num becomes 0
    while (num > 0) {
        // Calculate the remainder
        int rem = num % 8;
        // Append the remainder at the beginning
        str = to_string(rem) + str;
        // Divide the integer by 8
        num /= 8;
    }
    // Return the integer part
    return str;
}
 
// Function to convert the fractional part
string convertFractional(double num, int p)
{
    // Initialize the string
    string str = ".";
    // Loop until p becomes 0
    while (p > 0) {
        // Perform the steps as discussed above
        num *= 8;
        int integer = (int)(num);
        str += to_string(integer);
        num -= integer;
        p--;
    }
    // Return the fractional part
    return str;
}
 
// Function to convert float decimal to octal
string decimalToOctal(double num, int p)
{
    // Extract the integer part
    int integer = (int)(num);
    // Extract the fractional part
    double dec = num - integer;
    // Function call
    string s1 = convertInteger(integer);
    string s2 = convertFractional(dec, p);
    // Return the final answer
    return s1 + s2;
}
 
// Driver code
int main()
{
    double num = 123.45;
    int p = 2;
    string ans = decimalToOctal(num, p);
 
    // Function Call
    cout << "Octal Number: " << ans << endl;
    return 0;
}


Java




import java.util.*;
public class GFG {
    // Function to convert the integer part
    static String convertInteger(int num)
    {
        // Initialize an empty string
        StringBuilder str = new StringBuilder();
        // Loop until num becomes 0
        while (num > 0) {
            // Calculate the remainder
            int rem = num % 8;
            // Append the remainder at the beginning
            str.insert(0, rem);
            // Divide the integer by 8
            num /= 8;
        }
        // Return the integer part
        return str.toString();
    }
 
    // Function to convert the fractional part
    static String convertFractional(double num, int p)
    {
        // Initialize the string
        StringBuilder str = new StringBuilder(".");
        // Loop until p becomes 0
        while (p > 0) {
            // Perform the steps as discussed above
            num *= 8;
            int integer = (int)num;
            str.append(integer);
            num -= integer;
            p--;
        }
        // Return the fractional part
        return str.toString();
    }
 
    // Function to convert float decimal to octal
    static String decimalToOctal(double num, int p)
    {
        // Extract the integer part
        int integer = (int)num;
        // Extract the fractional part
        double dec = num - integer;
        // Function call
        String s1 = convertInteger(integer);
        String s2 = convertFractional(dec, p);
        // Return the final answer
        return s1 + s2;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        double num = 123.45;
        int p = 2;
        String ans = decimalToOctal(num, p);
 
        // Function Call
        System.out.println("Octal Number: " + ans);
    }
}


Python3




# Python Implementation
# Function to convert the integer part
def convert_integer(num):
    # Initialize an empty string
    str_val = ""
    # Loop until num becomes 0
    while num > 0:
        # Calculate the remainder
        rem = num % 8
        # Append the remainder at the beginning
        str_val = str(rem) + str_val
        # Divide the integer by 8
        num //= 8
    # Return the integer part
    return str_val
 
# Function to convert the fractional part
def convert_fractional(num, p):
    # Initialize the string
    str_val = "."
    # Loop until p becomes 0
    while p > 0:
        # Perform the steps as discussed above
        num *= 8
        integer = int(num)
        str_val += str(integer)
        num -= integer
        p -= 1
    # Return the fractional part
    return str_val
 
# Function to convert float decimal to octal
def decimal_to_octal(num, p):
    # Extract the integer part
    integer = int(num)
    # Extract the fractional part
    dec = num - integer
    # Function call
    s1 = convert_integer(integer)
    s2 = convert_fractional(dec, p)
    # Return the final answer
    return s1 + s2
 
# Driver code
if __name__ == "__main__":
    num = 123.45
    p = 2
    ans = decimal_to_octal(num, p)
 
    # Function Call
    print("Octal Number:", ans)
 
 
# This code is contributed by Sakshi


C#




using System;
 
class Program {
    // Function to convert the integer part to octal
    static string ConvertInteger(int num)
    {
        // Initialize an empty string
        string str = "";
        // Loop until num becomes 0
        while (num > 0) {
            // Calculate the remainder
            int rem = num % 8;
            // Append the remainder at the beginning
            str = rem + str;
            // Divide the integer by 8
            num /= 8;
        }
        // Return the integer part
        return str;
    }
 
    // Function to convert the fractional part to octal
    static string ConvertFractional(double num, int p)
    {
        // Initialize the string
        string str = ".";
        // Loop until p becomes 0
        while (p > 0) {
            // Perform the steps as discussed above
            num *= 8;
            int integer = (int)(num);
            str += integer;
            num -= integer;
            p--;
        }
        // Return the fractional part
        return str;
    }
 
    // Function to convert float decimal to octal
    static string DecimalToOctal(double num, int p)
    {
        // Extract the integer part
        int integer = (int)(num);
        // Extract the fractional part
        double dec = num - integer;
        // Function calls
        string s1 = ConvertInteger(integer);
        string s2 = ConvertFractional(dec, p);
        // Return the final answer
        return s1 + s2;
    }
 
    // Driver code
    static void Main()
    {
        double num = 123.45;
        int p = 2;
        string ans = DecimalToOctal(num, p);
 
        // Display the result
        Console.WriteLine("Octal Number: " + ans);
    }
}


Javascript




// javaScript code for the above approach
// Function to convert the integer part
function convertInteger(num) {
    let str = '';
    while (num > 0) {
        const rem = num % 8;
        str = rem.toString() + str;
        num = Math.floor(num / 8);
    }
    return str;
}
 
// Function to convert the fractional part
function convertFractional(num, p) {
    let str = '.';
    while (p > 0) {
        num *= 8;
        const integer = Math.floor(num);
        str += integer.toString();
        num -= integer;
        p--;
    }
    return str;
}
 
// Function to convert float decimal to octal
function decimalToOctal(num, p) {
    const integer = Math.floor(num);
    const dec = num - integer;
    const s1 = convertInteger(integer);
    const s2 = convertFractional(dec, p);
    return s1 + s2;
}
 
// Driver code
const num = 123.45;
const p = 2;
const ans = decimalToOctal(num, p);
 
// Output
console.log("Octal Number: " + ans);


Output

Octal Number: 173.34

Time Complexity: O(N), there will n iterations depending upon the number of digits in the float decimal number.
Auxiliary Space: O(N), We use an extra space for strings here, hence we require O(N) space.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads