0
votes

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
2
@amdixon: Doesn't answer the question.gnasher729
Dale Hagglund's answer in that post gives the solution to use roundf in combination with multipliplication by order of 10s ( according to your number of decimal places )amdixon
stackoverflow.com/questions/1343890/… The above link may help youSharon
stackoverflow.com/questions/1343890/… The above link may help youSharon

2 Answers

4
votes

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.

1
votes

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.