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.
- 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.
- Extract integer part from floating-point or double number.
- First, convert integer part to the string.
- Extract fraction part by exacted integer part from n.
- If d is non-zero, then do the following.
- Convert fraction part to an integer by multiplying it with pow(10, d)
- Convert the integer value to string and append to the result.
Following is C implementation of the above approach.
Note: The program performs similar operation if instead of float, a double type is taken.
This article is contributed by Jayasantosh Samal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- How to count set bits in a floating point number in C?
- Rounding Floating Point Number To two Decimal Places in C and C++
- Can we use % operator on floating point numbers?
- C Program to Multiply two Floating Point Numbers
- Floating Point Operations & Associativity in C, C++ and Java
- Problem in comparing Floating point numbers and how to compare them correctly?
- C++ Floating Point Manipulation (fmod(), remainder(), remquo() ... in cmath)
- Write a one line C function to round floating point numbers
- Precision of floating point numbers in C++ (floor(), ceil(), trunc(), round() and setprecision())
- What is the best way in C to convert a number to a string?
- How to convert a single character to string in C++?
- gcvt() | Convert float value to string in C
- Convert character array to string in C++
- C++ Program to Convert String to Integer
- Convert string to char array in C++
- How to convert C style strings to std::string and vice versa?
- sizeof() for Floating Constant in C
- Rotation of a point about another point in C++
- Converting string to number and vice-versa in C++
- C program to count number of vowels and consonants in a String
Improved By : shubham_singh