Quick actions

cmd+k|ctrl+k

Navigation

Languages

print float simple

Snippet info

Language

Cpp

Visibility

public

Author

evine

Created

2018-10-20T10:39:17Z

Updated

2018-10-23T19:58:23Z

#include <stdio.h>
#include <stdint.h>
#include <math.h>

void print_upper(double v, size_t i) {
    if(i == 0 || v >= 1) {
        print_upper(v / 10, i + 1);
        putchar('0' + (size_t)fmod(v, 10));
    }
}

void print_lower(double v_raw, size_t c) {
    bool pdot = false;
    size_t np = 0;
    
    size_t acc = 10;
    for(size_t i = 0; i < c; ++i) {
        double v = v_raw * acc;
        
        size_t pv = (size_t)fmod(v, 10);
        
        if(pv == 0) {
            np += 1;
        } else {
            if(pdot == false) {
                putchar('.');
                pdot = true;
            }
            
            for(size_t j = 0; j < np; ++j) {
                putchar('0');
            }
            np = 0;
            putchar('0' + pv);
        }
        
        acc *= 10;
    }
}

void print_float(double v) {
    if(*(uint64_t *)&v & 0x8000000000000000) {
        putchar('-');
        v = -v;
    }
    print_upper(v + 0.0005, 0);
    print_lower(v + 0.0005, 3);
}

void pf(double v) {
    print_float(v); putchar('\n'); 
}

int main() {
    uint64_t negative_zero = 0x8000000000000000;
    pf(*(double *)&negative_zero);
    pf(0);
    pf(-9.1235);
    pf(-9.1234);
    pf(5561134);
    pf(29.9995);
    pf(700.0);
    
    return 0;
}
INFO