Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print double in scientific format with no integer part

A simple problem but I can't get documentation about this kind of format: I want to print a float in a Fortran scientific notation, with its integer part always being zero.

 printf("%0.5E",data); // Gives 2.74600E+02

I want to print it like this:

 .27460E+03

How can I get this result as clean as possible?

like image 786
avances123 Avatar asked Sep 28 '22 15:09

avances123


1 Answers

If you only care about the integer part being 0 and not really leaving out the 0, i.e. if you're fine with 0.27460E+03 instead of .27460E+03 you could do something similar to this:

#include <stdio.h>
#include <stdlib.h>

void fortran_printf();

int main(void)
{
        double num = 274.600;
        fortran_printf(num);

        exit(EXIT_SUCCESS);
}

void fortran_printf(double num)
{
        int num_e = 0;
        while (num > 1.0) {
                num /= 10;
                num_e++;
        }

        printf("%.5fE+%02d", num, num_e);
}

Otherwise you have to take a detour over strings. Note that the code above is only meant to get you started. It certainly doesn't handle any involved cases.

like image 55
lord.garbage Avatar answered Oct 15 '22 11:10

lord.garbage