Convert a floating point number to string
Given a float number convert it into the string WITHOUT using any inbuilt Function
Method 1:
class Float2String { public static void main(String[] args) { float f=7.64f; String result; result=""+f; System.out.println(result); } }
-by karthik dheeraj
Method 2:
#include<stdio.h> #include<math.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[]. 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; } // Converts a floating point number to string. 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] = '.'; // add dot // Get the value of fraction part upto given no. 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("\n\"%s\"\n", res); return 0; }