using setprecision without fixed or scientific format. – Computer Sir Ki Class Code Learning #CPP#4326   ## using setprecision without fixed or scientific format.

setprecision to set number of digits for any decimal containing floating number.

## Learning Objectives

• Effect of using setprecision on floating numbers in float/double format.

## Source Code

 #include #include using namespace std; int main() { double d=123.5613; cout<

## Run Output

``````123.551
123.6
123.5513
123.5513
124
1.2e+02

Output in TurboC++ DOS
123.5513
123.5513
123.5513
123.5513
123.551
123.55

This is because setprecision works for digits after decimal only for TurboC type of compiler.
``````

## Code Understanding

double d=123.5513;
This number will be used to apply precision formatting on. It has 3 digits before decimal and 4 digits after decimal. Total 7 digits.

cout<<d<<endl;
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.

cout<<setprecision(4)<<d<<endl;
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.

cout<<setprecision(7)<<d<<endl;
Here all the 7 digits will print as 123.5513  as the original number has 7 digits and precision is also set to 7.

cout<<setprecision(8)<<d<<endl;
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

cout<<setprecision(3)<<d<<endl;
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.

cout<<setprecision(2)<<d<<endl;
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.

## Notes

Suggested Filename(s): setprecision.cpp

sunmitra| Created: 18-May-2018 | Updated: 28-Aug-2018|

×