Prog
Prog

Reputation: 31

In C++ : how to print the digits after the decimal.

In C++ : how to print the digits after the decimal. For example i have this float number ( 12.54 ), and i want to print it like this ( 0.54 ). Thank you all.

Upvotes: 2

Views: 229

Answers (3)

Dmytro Dadyka
Dmytro Dadyka

Reputation: 2260

The simplest way

float f = 10.123;
float fract = f - (int)f;
std::cout << fract;

But for large input you can obtain integer overflow. In this case use

float fract = f - truncf(f);

Output

0.123

Upvotes: 4

doug
doug

Reputation: 4299

In C++ : how to print the digits after the decimal. For example i have this float number ( 12.54 ), and i want to print it like this ( 0.54 ).

If you want to use get the fractional part of a floating type number you have a choice of std::floor or std::trunc. Non negative numbers will be treated the same by either but negative numbers will not.

std::floor returns the lowest, non fractional, value while std::trunc returns the non fractional towards 0.

double f=1.23;
floor(f);  // yields .23
trunc(1.23);  // also yields .23

However

double f=-1.23;
floor(f);  // yields -2
trunc(f);  // but yields -1

So use trunc to get the fractional part for both positive and negative f's:

double f=-1.23;
f - floor(f);  // yields .77
f - trunc(f);  // but yields -.23

Upvotes: 1

Vikas Agarwal
Vikas Agarwal

Reputation: 82

You can use modf function.

double integral_part;
double fractional = modf(some_double, &integral_part);

You can also cast it to an integer, but be warned you may overflow the integer. The result is not predictable then.

Upvotes: 4

Related Questions