Write a C function ftoa() that converts a given floating point number to string. Use of standard library functions for direct conversion is not allowed. The following is prototype of ftoa().
ftoa(n, res, afterpoint) n --> Input Number res --> Array where output string to be stored afterpoint --> Number of digits to be considered after point. For example ftoa(1.555, str, 2) should store "1.55" in res and 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.
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.
2) First convert integer part to string.
3) Extract fraction part by exacted integer part from n.
4) If d is non-zero, then do following.
….a) Convert fraction part to integer by multiplying it with pow(10, d)
….b) Convert the integer value to string and append to the result.
Following is C implementation of the above approach.
// C program for implementation of ftoa()
// reverses a string 'str' of length 'len'
i=0, j=len-1, temp;
temp = str[i];
str[i] = str[j];
str[j] = temp;
// Converts a given integer x to string str. d is the number
// of digits required in output. If d is more than the number
// of digits in x, then 0s are added at the beginning.
i = 0;
str[i++] = (x%10) +
x = x/10;
// If number of digits required is more, then
// add 0s at the beginning
(i < d)
// Converts a floating point number to string.
// Extract integer part
ipart = (
// Extract floating part
fpart = n - (
// convert integer part to string
i = intToStr(ipart, res, 0);
// check for display option after point
(afterpoint != 0)
// 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 *
)fpart, res + i + 1, afterpoint);
// driver program to test above funtion
n = 233.007;
ftoa(n, res, 4);
Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits: http://www.geeksforgeeks.org
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at
http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements