Program to convert float decimal to Octal number
Last Updated :
11 Jan, 2024
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);
OutputOctal 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.
Similar Reads
Program to convert a binary number to octal
The problem is to convert the given binary number (represented as string) to its equivalent octal number. The input could be very large and may not fit even into unsigned long long int. Examples: Input : 110001110 Output : 616 Input : 1111001010010100001.010110110011011 Output : 1712241.26633 The id
9 min read
Program to Convert Octal Number to Binary Number
Given an Octal number as input, the task is to convert that number to Binary number. Examples: Input : Octal = 345Output : Binary = 11100101Explanation : Equivalent binary value of 3: 011Equivalent binary value of 4: 100Equivalent binary value of 5: 101 Input : Octal = 120Output : Binary = 1010000 O
9 min read
How to convert a rational number to a decimal?
Answer: Here are the steps to convert fractions to decimals :Make the fraction an incorrect fraction if it's a mixed number.Subtract the denominator from the numerator.Round the decimal off if the division does not come out evenly.A number System can be defined as a system of writing to express numb
4 min read
Program for decimal to hexadecimal conversion
Given a decimal number as input, we need to write a program to convert the given decimal number into an equivalent hexadecimal number. i.e. convert the number with base value 10 to base value 16.Hexadecimal numbers use 16 values to represent a number. Numbers from 0-9 are expressed by digits 0-9 and
8 min read
How to Convert Number to String
Given a numerical value, convert it into a string representation. In this article, we will provide a detailed overview about different ways to convert Number to String in different languages. Table of Content Convert Number to String in CConvert Number to String in C++Convert Number to String in Jav
7 min read
How to Convert String to Number
Given a string representation of a numerical value, convert it into an actual numerical value. In this article, we will provide a detailed overview about different ways to convert string to number in different languages. Table of Content Convert String to Number in CConvert String to Number in C++Co
5 min read
Program for Binary To Decimal Conversion
Given a binary number as input, we need to write a program to convert the given binary number into an equivalent decimal number.Examples : Input : 111Output : 7Explanation : The output of 7 for input 111 represents the decimal equivalent of the binary number 111.Input : 1010Output : 10Explanation :
15 min read
Convert Decimal To Mixed Number
Decimals are numbers that lie between integers on a number line. Decimals are another method to express fractions. The numbers to the left of the decimal point are integers or whole numbers, while the numbers to the right are decimal fractions. If we proceed right from one place, the following place
7 min read
Convert decimal fraction to binary number
Given a fraction decimal number n and integer k, convert decimal number n into equivalent binary number up-to k precision after decimal point. Examples: Input: n = 2.47, k = 5Output: 10.01111Input: n = 6.986 k = 8Output: 110.11111100We strongly recommend that you click here and practice it, before m
9 min read
How to convert a whole number into a decimal?
Answer: To convert a whole number into a decimal, simply add a decimal point and zero after the number. For Example:Given that the whole number is 5.Add a decimal and a zeros to the right side of the whole number.5 = 5.0Hence, the decimal number is 5.0Also Read : Convert Decimal To Mixed NumberHow t
5 min read