Convert a floating point number to string in C/C++

Write a C/C++ function to convert a float into string .

Prototype of function :
char* floatToString(float input , int n ) ; where
input -> your float input .
n -> it is the number of digit considered after decimal .
Example : (2.345,2) => output will be "2.34"

Soutions 1 : Easy one

{
 char *str = new char[100] ;
 sprintf(str,"%f",x);
 return str ;
}

Solution 2 : Without using any library
step 1 – Break the input into two part , integer before decimal and after decimal .
step 2 – convert both part into string and join them with a decimal .

//funtion to convert int to string 
int intToString(int x, char str[], int d)
{
    int i = 0;
    while (x)
    {
        str[i++] = (x%10) + '0';
        x = x/10;
    }
 
    // If number of digits required is more, then
    // add 0s at the beginning
    while (i < d)
        str[i++] = '0';
 
    reverse(str, i);
    str[i] = '\0';
    return i;
}
 
//function to convert float to string
char* floatToString(float input , int n ) 
{
    int int_part = (int)input;
    float float_part = input - (float)int_part;
    char *str = new char[100] ;
  
    // convert integer part to string
    int i = intToString(int_part, str, 0);
 
    // check for display option after point
    if (n != 0)
    {
        str[i] = '.';  // 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
        float_part = float_part * pow(10, n);
 
        intToString((int)float_part, res + i + 1, n);
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

For Inserting code :
Paste your code in the comment form, select it and then click the language link

C | C++ | Java |

*