nofe
nofe

Reputation: 408

Printing a very large whole number in C

I've stored a very large number in a float variable, but when I print it I want to only display the whole number part and nothing after the decimal point.

For numbers in the int or long range, I would do a casting but this hasn't helped me because the number I want to print is too long for int or long.

I've looked at this explanation: http://www.cprogramming.com/tutorial/printf-format-strings.html but I haven't succeeded in solving this.

this is my code and my attempt to do the casting:

double sum=552074001368;
long long_sum;
long_sum = (long)(sum);      //int casting for double "add" 
if(sum>=0) printf("=\n%ld\n",long_sum);
else printf("=\n%ld\n",-long_sum);

I don't want to use a specific precision like printf("%15f") because this variable fluctuates and is sometimes very short like 4 digits.

Upvotes: 1

Views: 1205

Answers (5)

BLUEPIXY
BLUEPIXY

Reputation: 40145

double sum=552074001368LL;
long long long_sum;
long_sum = (long long)(sum);
if(sum>=0) printf("=\n%lld\n",long_sum);
else printf("=\n%lld\n",-long_sum);

Upvotes: 0

Lundin
Lundin

Reputation: 213711

This line is problematic:

double sum=552074001368;

Since that is an integer literal, the compiler will first check if the number will fit in an int, then long, then long long. If it won't fit in long long I suspect you'll get either a compiler error or undefined behavior wrap-around, I'm not sure of which.

If your compiler supports long long, then the code will work and the number will be stored in a temporary long long (which will be optimized away). This long long is then stored inside a double.

Instead, write like this:

double sum=552074001368.0;

The .0 syntax gives you a double floating point literal without involving integer types at all.

Upvotes: 0

reactor
reactor

Reputation: 1

Why are you casting to long at all? Use the printf format specifiers to control what and how many characters are printed. http://www.cplusplus.com/reference/clibrary/cstdio/printf/

Remember that both the width and the precision can be specified by a variable and doesn't have to be known at compile time:

printf("=\n%.*lf\n", 4, sum); // print 4 places behind the decimal point

 int i;
 i = 5;
// print only the whole number part of sum and output at least i characters,
//    pad with leading spaces if number requires fewer than i characters 
printf("=\n%*.*lf\n", i, 0, sum); 

Upvotes: 0

Jerry Coffin
Jerry Coffin

Reputation: 490108

I think what you're after is %.0f. For example:

#include <stdio.h>

int main(){

    double x = 1234.567;

    printf("%.0f", x);
    return 0;
}

...prints:

1235

Upvotes: 5

Fred Foo
Fred Foo

Reputation: 363547

Use the precision modifier .0 and print the floor of the number:

printf("%.0f\n", floor(sum));

(Or the floor of the abs, if you want only the magnitude, as in your example code.)

Upvotes: 6

Related Questions