Convert double number to 3 decimal places number in C++
In this tutorial, we’ll be going over two methods of converting a double with any number of decimal places to a double with decimal places. The first method is arithmetic and changes the value of the double stored in the memory whereas the second method is using the setprecision()
function which prints the double up to three decimal places after rounding off without actually changing the value of the double stored in the memory.
First Method: Arithmetically rounding off the double to three decimal places
#include <iostream> #include <cmath> using namespace std; int main() { double a; cin>>a; int count=0; double temp=a; while(temp-int(temp)!=0){ temp=temp*10; count++; } if(count<=3){ cout<<a<<endl; } else if(count>=4){ int b=int(temp/pow(10,count-4)); if(b%10>=5) b+=(10-(b%10)); a=int(b/10)/pow(10,3); cout<<a<<endl; } return 0; }
The while loop counts the number of decimal places in the double and using the temp variable that initially has the same value as our double is converted to an integer using repeated multiplication by 10. If the count is less than or equal to 3, then it just simply prints the value of the double without changing it. If the value of count is greater than 3, it initializes a variable b with the integer value of the number formed after shifting the decimal four spaces to the right of the original double. Then it takes the last digit of b and checks whether it is greater than, equal to or less than 5 in order to round off correctly. After rounding off it just divides the integer value of b/10 by 10^3 in order to convert it to the original value after rounding it off.
Second Method: Rounding off to three decimal places while printing
int main(){ double n; cin>>n; double temp=n; int count=0; while(int(temp)/1!=0){ temp=temp/10; count++; } cout<<setprecision(count+3)<<n<<endl; return 0; }
This method first counts the number of digits before the decimal in the double and then uses the member function setprecision() of the header file “iomanip.h”. This method sets the number of digits of a numerical value to be used in the input and output streams. This is the reason for setting the precision as count+3, in order to account for three decimal places and this function also rounds off the double itself according to the precision that was set.
Input
1.2765 3.12435
Output
1.277 3.124
Leave a Reply