Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
want to print a fractional digits seperately and how many fractionals are in floating point numbers without using typecast..
eg: u should have this statement in ur pgm : float f=345.876;
then output should be
o/p:8 7 6 and 3
the algorithm i need which is working for all floating numbers
Posted
Updated 8-Aug-13 23:46pm
v2
Comments
Richard MacCutchan 9-Aug-13 6:06am    
Use sprintf to convert it into its character representation and then extract the digits after the decimal point. You can use strstr, strtok or similar, to extract the fields you want.

1 solution

Something like this might work for you (might want to clean it up);

C
#include <stdio.h>
#include <string.h>

int main()
{
    char result[128];
    char buffer[128];
    float f = 345.876f;
    sprintf(buffer,"%f",f);

    int count = 0;
    int r = 0;
    int found_point = 0;
    for(int i = 0; i < 128 && buffer[i] != 0; ++i) {
        if (found_point) {
            result[r] = buffer[i];
            result[++r] = ' ';
            result[++r] = 0;
            ++count;
        }
        else {
            found_point = buffer[i] == '.' ? 1 : 0;
        }
    }

    if (count > 0) {
        strcpy(result + r, "and ");
        char c_buffer[128];
        sprintf(c_buffer, "%d", count);
        strcpy(result + strlen(result), c_buffer);
    }

    printf("o/p: %s\r\n", result);

    return 0;
}


Hope this helps,
Fredrik
 
Share this answer
 
Comments
Maciej Los 9-Aug-13 9:06am    
You're too kind to OP ;)
+5!
Fredrik Bornander 9-Aug-13 9:16am    
True, but it's his/hers first question so I think he/she deserves a little slack :)
nv3 9-Aug-13 9:20am    
That won't work for values that do not have an exact representation as float or double, for example 0.1. In many cases your program will give a very high number of decimals that originated just from the representation as binary fraction. OP probably does not understand that floating point values are stored in a different format and hence the some decimal values cannot be stored exactly in the floating point format of our today's CPUs.
Fredrik Bornander 9-Aug-13 9:26am    
I know, even the example I posted prints 6 decimals for the input given.
But if the input is a float it's going to be very difficult to work around that.
nv3 9-Aug-13 9:31am    
How about limiting the number of fractionals to one less than the precision of the float format. Then sprintf rounds for you and you only have to suppress any trailing zeros.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900