开发者

Printing a double without the decimal places

开发者 https://www.devze.com 2023-03-22 18:15 出处:网络
I have a number stored as a double and want to print it without the decimal places.So if I had the double value 91954563开发者_运维知识库4521.000000, it is always printed with the decimal places added

I have a number stored as a double and want to print it without the decimal places. So if I had the double value 91954563开发者_运维知识库4521.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);
}


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).


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.


Use %0.0lf or go with an integer

Lookup format specs for printf


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


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


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


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' ;

}
0

精彩评论

暂无评论...
验证码 换一张
取 消