Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++ Data Types
  • C++ Input/Output
  • C++ Arrays
  • C++ Pointers
  • C++ OOPs
  • C++ STL
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ MCQ
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
Open In App
Next Article:
gcvt() | Convert float value to string in C
Next article icon

Convert a floating point number to string in C

Last Updated : 21 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Write a C function ftoa() that converts a given floating-point number or a double to a string.  Use of standard library functions for direct conversion is not allowed. The following is prototype of ftoa(). The article provides insight of conversion of C double to string.

ftoa(n, res, afterpoint) n          --> Input Number res[]      --> Array where output string to be stored afterpoint --> Number of digits to be considered after the point.

Example:

  • ftoa(1.555, str, 2) should store “1.55” in res.
  • ftoa(1.555, str, 0) should store “1” in res.

We strongly recommend to minimize the browser and try this yourself first. A simple way is to use sprintf(), but use of standard library functions for direct conversion is not allowed. Approach: The idea is to separate integral and fractional parts and convert them to strings separately. Following are the detailed steps.

  1. Extract integer part from floating-point or double number.
  2. First, convert integer part to the string.
  3. Extract fraction part by exacted integer part from n.
  4. If d is non-zero, then do the following.
    1. Convert fraction part to an integer by multiplying it with pow(10, d)
    2. Convert the integer value to string and append to the result.

Following is C implementation of the above approach. 

C




// C program for implementation of ftoa()
#include <math.h>
#include <stdio.h>
 
// Reverses a string 'str' of length 'len'
void reverse(char* str, int len)
{
    int i = 0, j = len - 1, temp;
    while (i < j) {
        temp = str[i];
        str[i] = str[j];
        str[j] = temp;
        i++;
        j--;
    }
}
 
// Converts a given integer x to string str[].
// d is the number of digits required in the output.
// If d is more than the number of digits in x,
// then 0s are added at the beginning.
int intToStr(int x, char str[], int d)
{
    int i = 0;
    while (x) {
        str[i++] = (x % 10) + '0';
        x = x / 10;
    }
 
    // If number of digits required is more, then
    // add 0s at the beginning
    while (i < d)
        str[i++] = '0';
 
    reverse(str, i);
    str[i] = '\0';
    return i;
}
 
// Converts a floating-point/double number to a string.
void ftoa(float n, char* res, int afterpoint)
{
    // Extract integer part
    int ipart = (int)n;
 
    // Extract floating part
    float fpart = n - (float)ipart;
 
    // convert integer part to string
    int i = intToStr(ipart, res, 0);
 
    // check for display option after point
    if (afterpoint != 0) {
        res[i] = '.'; // add dot
 
        // Get the value of fraction part upto given no.
        // of points after dot. The third parameter
        // is needed to handle cases like 233.007
        fpart = fpart * pow(10, afterpoint);
 
        intToStr((int)fpart, res + i + 1, afterpoint);
    }
}
 
// Driver program to test above function
int main()
{
    char res[20];
    float n = 233.007;
    ftoa(n, res, 4);
    printf("\"%s\"\n", res);
    return 0;
}
 
 
Output:
"233.0070"

Time Complexity: O(logn)

Auxiliary Space: O(1)

Note: The program performs similar operation if instead of float, a double type is taken.



Next Article
gcvt() | Convert float value to string in C

J

Jayasantosh Samal
Improve
Article Tags :
  • C Language
  • C++
  • cpp-data-types
  • cpp-string
Practice Tags :
  • CPP

Similar Reads

  • Converting Number to String in C++
    In C++, converting integers to strings or converting numbers to strings or vice-versa is actually a big paradigm shift in itself. In general or more specifically in competitive programming there are many instances where we need to convert a number to a string or string to a number. Let's look at som
    4 min read
  • How to count set bits in a floating point number in C?
    Given a floating point number, write a function to count set bits in its binary representation. For example, floating point representation of 0.15625 has 6 set bits (See this). A typical C compiler uses single precision floating point format. We can use the idea discussed here. The idea is to take a
    2 min read
  • Rounding Floating Point Number To two Decimal Places in C and C++
    How to round off a floating point value to two places. For example, 5.567 should become 5.57 and 5.534 should become 5.53 First Method:- Using Float precision [GFGTABS] C++ #include<bits/stdc++.h> using namespace std; int main() { float var = 37.66666; // Directly print the number with .2f pre
    2 min read
  • Convert String to int in C++
    Converting a string to int is one of the most frequently encountered tasks in C++. As both string and int are not in the same object hierarchy, we cannot perform implicit or explicit type casting as we can do in case of double to int or float to int conversion. Conversion is mostly done so that we c
    7 min read
  • gcvt() | Convert float value to string in C
    Here, we shall see how a float number (floating point value) can be converted to the string in C language. It is a library function defined in stdio.h header file. This function is used to convert a floating point number to string. Syntax : gcvt (float value, int ndigits, char * buf); float value :
    2 min read
  • Write a one line C function to round floating point numbers
    Algorithm: roundNo(num) 1. If num is positive then add 0.5. 2. Else subtract 0.5. 3. Type cast the result to int and return. Example: num = 1.67, (int) num + 0.5 = (int)2.17 = 2 num = -1.67, (int) num - 0.5 = -(int)2.17 = -2 Implementation: /* Program for rounding floating point numbers */ # include
    1 min read
  • What is the best way in C to convert a number to a string?
    Solution: Use sprintf() function. #include<stdio.h> int main() { char result[50]; float num = 23.34; sprintf(result, "%f", num); printf("\n The string for the num is %s", result); getchar(); } You can also write your own function using ASCII values of numbers.
    1 min read
  • Precision of Floating Point Numbers in C++ (floor(), ceil(), trunc(), round() and setprecision())
    The decimal equivalent of 1/3 is 0.33333333333333…. An infinite length number would require infinite memory to store, and we typically have 4 or 8 bytes. Therefore, Floating point numbers store only a certain number of significant digits, and the rest are lost. The precision of a floating-point numb
    4 min read
  • Number System Conversion in C
    Number system conversion is a fundamental concept in computer science and programming. It involves changing the representation of a number from one base to another, such as converting a decimal number to binary or a hexadecimal number to binary. In this article, we will create a console program in t
    8 min read
  • sizeof() for Floating Constant in C
    In C language, we have three floating data types i.e. float, double and long double. And the exact size of each of these 3 types depends on the C compiler implementation/platform. The following program can be used to find out the size of each floating data type on your machine. C/C++ Code #include
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences