-1
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
  double a,b,result;
  a = 2;b = 3;
  result = a / b;
  cout << fixed << setprecision(2) << result;

}

the output of this code in my IDE is :

0.67

i want the output to be

0.66

what do i do to change it to that

3 Answers3

2

Since you want truncation while setprecision uses rounding, you need to truncate the result manually:

cout << fixed << setprecision(2) << trunc(100*result)/100;

Multiplying and dividing by 100 keeps two decimal digits in place.

Demo.

Note 1: You have to be careful not to pass numbers that are close to the top of double's range to avoid overflowing on multiplication.

Note 2: You can generalize this approach by multiplying and dividing by pow(10,n) where n is the number of decimal digits that you wish to keep.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

2 / 3 is 0.666666666..., which is indeed closer to 0.67 than to 0.66. So if you want to the latter, you have to actually change the result. You can do this using a simple function:

double truncate(double val, int precision)
{
  double shift = std::pow(10.0, precision);
  return std::trunc(val * shift) / shift;
}
Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
0

You could try truncating with following:

result = (int)( 100 * a / b ) / 100.0; 
Tom de Geus
  • 5,625
  • 2
  • 33
  • 77
StPiere
  • 4,113
  • 15
  • 24