Friday, July 31, 2009

Round double/floats to fixed number of decimal places?

say i have


double val1 = 20.12345678987;


double val2 = 0.0;





in C / C++ , i want to have val2 = 20.123 ... rounding off val1 to 3 decimal places. How can i do this? its not for output, so nto using cout %26lt;%26lt; setprecision.

Round double/floats to fixed number of decimal places?
Yes you can do it via following logic, I have checked in Java but it should work in C / C++ but at least you can get the idea.





val2 = (double) (((int) (val1 * 1000)) / 1000.00); //it will limit to 3 digits after decimal.





Now you can print val2 on screen or use it anywhere without using set-precision or any other function it will show three digits after decimal.





You can limit to any decimal places like following:





val2 = (double) (((int) (val1 * 100)) / 100.00); //it will limit to 2 digits after decimal.





val2 = (double) (((int) (val1 * 10000)) / 10000.00); //it will limit to 4 digits after decimal.





val2 = (double) (((int) (val1 * 100000)) / 100000.00); //it will limit to 5 digits after decimal.





Hope answered your question.





--------------------------------------...


Whenever you will take input from user you will have to manipulate it...anyway....Can you send me your program?


No comments:

Post a Comment