using setprecision without fixed or scientific format.
setprecision to set number of digits for any decimal containing floating number.
- Effect of using setprecision on floating numbers in float/double format.
using namespace std;
Test it !
Test it !
Before using this you should have copied the code by selecting the entire code and pressing cntrl-c. (Line numbers will not come in the copied code). After that open any of the service and press cntrl-v to paste in the given code area. Needs a bit of tweaking as per the link.
This number will be used to apply precision formatting on. It has 3 digits before decimal and 4 digits after decimal. Total 7 digits.
This should print 123.551 as default precision for a floating number is 6 digits. If the last digit would be 6 or more than the rounding off previous digit would have happened to higher number.
Here we are setting precision of 4 digits so the only 4 digits in a most significant way would be printed. This will print 123.6 as 4 digits are to be printed and after decimal rounding off rules will apply for any subsequent digits of 5 or more.
Here all the 7 digits will print as 123.5513 as the original number has 7 digits and precision is also set to 7.
Here again all the digits will print as it is as precision is set to more than required 7 digits. So output would be 123.5513
Here 124 will print as rounding off rules will apply and 5 being immediately after decimal will effect the number 3 just before decimal to become 4 due to rounding off.
Since in this case the precision is less than the non decimal part, so the number will attempt to print itself to a nearest scientific format number as 1.2e+02 which means 1.2 multiplied by 10 raised to power two which is basically equivalent to 120. Had this been 125.xxx then the output would have been 1.3e+02 which is equivalent to 130. Again the effect of rounding off can be noticed.
Note: Above explanation has been given for modern compilers and not for things like Turboc++ DOS version which takes into account the digits after decimal only and thus the output is different as shown in the output section.
- Behaviour of setprecision applies on all subsequent floating number outputs unless it is unset or its value is changed. Thus it is persistent in nature.
- This great article on setting io manipulation will help you a lot.
Suggested Filename(s): setprecision.cpp
sunmitra| Created: 18-May-2018 | Updated: 28-Aug-2018|