VOOZH about

URL: https://www.geeksforgeeks.org/cpp/convert-floating-point-number-string/

⇱ Convert a floating point number to string in C - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Convert a floating point number to string in C

Last Updated : 23 Jul, 2025

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. 

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.

Comment
Article Tags: