简体   繁体   中英

Round floating point:Print exactly two digits after the decimal point rounded to the nearest decimal place

How do we round a floating point number in C/C++ to print exactly two digits after the decimal point rounded to the nearest decimal place? say for example,when I use,

printf("%.2f", 12.555);
cout<<fixed<<setprecision(2)<<12.555<<endl;

I get,

12.55
12.55

but I need output as,

12.56
12.56

The problem is that the actual double value for 12.555 is

12.55499999999999971578290569595992565155029296875000

so when you round it to 2 decimal places it rounds down to 12.55. There's really nothing you can do about that.

C or C++ don't care about what you need.

12.555 is not a binary floating point number. Binary floating point numbers are all integers multiplied by or divided by a power of two. 12.555 is not such a number. So when you write 12.555 then what you get is the floating-point number nearest to 12.555. Which may be smaller or larger than 12.555 and will be correctly rounded to 12.55 or correctly rounded to 12.56.

Calculate x * 1000 and round (x * 1000), which will give 12555. If x * 1000 is very close to round (x * 1000) and the last digit of round (x * 1000) is odd then increase it by 1. Divide by 10, round again, divide by 100.

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