简体   繁体   中英

C++ Avoid Rounding Number

I know we can use setprecision to prevent a number to be rounded but what if I don't want to round all of my numbers in the list with the same decimal places? In other words, I want to keep my numbers the same as calculated and each number has its own decimal places.

For example: if we use setprecision(7) then it will give the output up to 7 decimal places for all numbers in my list. What if I have a list of different numbers with different decimal places such as 8 or 10 decimal places? Do I need to do setprecision for each of them? Is there any way to keep my numbers the same as the output after calculated? Ex:0.1234567, 0.123456789, 0.12345678910

#include<iostream>
#include<vector>
using namespace std;
int main()
{
   vector<double> myVec{0.1234567, 0.123456789, 0.12345678, 0.12345678910};

   for(int i = 0; i < myVec.size(); i++)
   {
       cout << myVec[i] << " ";
   }
   return 0;
}

Is there any way to keep my numbers the same as the output after calculated?

Not with floating point types such as double .

These are binary floating points, not decimal. Many exact finite decimal fractions will convert to infinite binary fraction, and rounding would happen. So after you do dobule d = 0.1234567 , the variable d will not contain exactly 0.1234567 , it is rather something close to 0.1234567 representable as double.

A way to deal with this is to have custom data types that are decimal fractions, with fixed or floating point, so that 0.1234567 could be represented exactly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM