How to print floating point value using putchar?

I am working on an embedded application and should print floating point values. Due to space and other limitations, I can use putchar () for output.

I am trying to create a function that takes a float parameter as a parameter and prints it using putchar (). I have a similar function that works for integer values.

void putLong(long x)
{
    if(x < 0)
    {
        putchar('-');
        x = -x;
    }
    if (x >= 10) 
    {
        putLong(x / 10);
    }
    putchar(x % 10+'0');
}

How can I make a similar function for float?

+3
source share
3 answers

Here a solution is possible:

typedef enum
{
    DEC1 = 10,
    DEC2 = 100,
    DEC3 = 1000,
    DEC4 = 10000,
    DEC5 = 100000,
    DEC6 = 1000000,

} tPrecision ;

void putFloat( float f, tPrecision p )
{
    long i = (long)f ;
    putLong( i ) ;
    f = (f - i) * p ;
    i = abs((long)f) ;
    if( fabs(f) - i >= 0.5f )
    {
        i++ ;
    }
    putchar('.') ;
    putLong( i ) ;
    putchar('\n') ;
}

You would use it this way:

putFloat( 3.14159f, DEC3 ) ;

which will output "3.142", note the rounding of the third digit.

, .

, 6 , . , , , 123.456, DEC6, . 6- , , , .

+2

/ ? 8 ( 2, ) , 80- 128- long double. , 1 kb , double , , , .

, :

void putDouble(double x, int p)
{
    long d;
    if (x<0) {
        putchar('-');
        x=-x;
    }
    d = x;
    putLong(d);
    putchar('.');
    while (p--) {
        x = (x - d) * 10;
        d = x;
        putchar('0'+d);
    }
}

, putLong 2 , 2.: -)

+1

, , float .

- , putLong, .

.

int float, . , , , 10, int putLong .

I suspect that there might be a more efficient or easier way to do this, but I'm sure this approach will work. Looking at how the float bits are used to represent exponential components and values ​​can also be useful.

0
source

Source: https://habr.com/ru/post/1778558/


All Articles