phoenix
phoenix

Reputation: 549

Printing a double without the decimal places

I have a number stored as a double and want to print it without the decimal places. So if I had the double value 919545634521.000000, it is always printed with the decimal places added to it. How can I print it without it so it looks like: 919545634521?

#include<stdlib.h>

int main()
{
    double number = 9220343120;
    printf("%??\n", number);
}

Upvotes: 13

Views: 42763

Answers (7)

Bayron Vazquez
Bayron Vazquez

Reputation: 371

if you use cpp you can indicate the precession of decimals with 'showpoint'. showpoint is a flag for std stream cout, look at the example to see the behavior of showpoint. You can also read the more detailed documentation here cpp reference


#include <iostream>

using namespace std;

int main()
{

// check out this example
for( double number : {34521.0010100, 1.0, 1.01, -1.0, -1.01, 0.0, 1.0e+10, -1.0001e-10 } )
     cout << "showpoint: " << showpoint << number << "  noshowpoint: " << noshowpoint << number << '\n' ;

}

Upvotes: 0

nevelis
nevelis

Reputation: 748

Not sure about other compiler support, but GCC supports the 'g' format specifier, which will print a double using the least space required for full precision. For example:

double d1 = 10.000;
double d2 = 25.03;
printf( "d1: %g\nd2: %g\n", d1, d2 );

will result in:

d1: 10
d2: 25.03

Upvotes: 0

Richard Holland
Richard Holland

Reputation: 2673

Use %0.0lf or go with an integer

Lookup format specs for printf

Upvotes: 4

NPE
NPE

Reputation: 500157

Well, don't store the phone number as a floating-point number (one wrong move, and you'll end up with your telephone numbers getting rounded for you).

Store it as an integer or a string.

Upvotes: 3

caf
caf

Reputation: 239011

You're looking for precision - the format specifier %.0f should do what you want.

Upvotes: 0

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143061

try

printf("%.0lf\n",phoneNum);

you may also prefer

long long phoneNum;
phoneNum = strtoll(buffer,NULL,0);
printf("%lld\n",phoneNum);

instead. Depending on the system, though, you may need other function to convert (I think it's _strtoui64 for windows).

Upvotes: 19

jman
jman

Reputation: 11586

printf ("%.0f\n", phoneNum); should work.

Upvotes: 2

Related Questions