简体   繁体   中英

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.

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM