Convert a floating point number to string in C
Last Updated :
21 Jun, 2022
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.
- 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.
C
#include <math.h>
#include <stdio.h>
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--;
}
}
int intToStr( int x, char str[], int d)
{
int i = 0;
while (x) {
str[i++] = (x % 10) + '0' ;
x = x / 10;
}
while (i < d)
str[i++] = '0' ;
reverse(str, i);
str[i] = '\0' ;
return i;
}
void ftoa( float n, char * res, int afterpoint)
{
int ipart = ( int )n;
float fpart = n - ( float )ipart;
int i = intToStr(ipart, res, 0);
if (afterpoint != 0) {
res[i] = '.' ;
fpart = fpart * pow (10, afterpoint);
intToStr(( int )fpart, res + i + 1, afterpoint);
}
}
int main()
{
char res[20];
float n = 233.007;
ftoa(n, res, 4);
printf ( "\"%s\"\n" , res);
return 0;
}
|
Time Complexity: O(logn)
Auxiliary Space: O(1)
Note: The program performs similar operation if instead of float, a double type is taken.
Share your thoughts in the comments
Please Login to comment...