+ 1

How to approximate the last decimal.

Please I'm running a program that requires the last digit of a decimal to be approximated, please how do I do this? For example: If variable n = 14.445; Output should be 14.45;

26th Dec 2022, 11:55 AM
DevAbdul
DevAbdul - avatar
3 Réponses
+ 4
Since printf() is a C function, the C++ version of that is std::cout.precision(2); // to round to 2 places std::cout << 0.878; // output: 0.88 (printf is fine too btw) To get the rounded value is not as direct as calling a function. There is a std::round() function in <cmath>, but that rounds to the nearest integer. https://cplusplus.com/reference/cmath/round/ To round a number to a specific decimal place, see the method described here https://stackoverflow.com/a/57459521
26th Dec 2022, 2:51 PM
XXX
XXX - avatar
+ 3
You could use a round() method or string formatting: printf("%.2f", 1.234);
26th Dec 2022, 12:05 PM
Lisa
Lisa - avatar
0
Thanks Lisa
26th Dec 2022, 1:50 PM
DevAbdul
DevAbdul - avatar