0

I want to set precision for float in C++. Suppose my code is

float a = 23.5, b = 24.36; float c = a + b;

and if I print this

cout << c;

It gives: 46.86

But I want to print till one digit after the decimal point. How to do that?

Oussama Ben Ghorbel
  • 2,132
  • 4
  • 17
  • 34
Sanket Singh
  • 101
  • 1
  • 3
  • 11

2 Answers2

3

You specify the minimum precision by using setprecision. And fixed will make sure there is a fixed number of decimal digits after the decimal point.

cout << setprecision (1) << fixed << c;
Oussama Ben Ghorbel
  • 2,132
  • 4
  • 17
  • 34
2

This example may hep you figure it out. You need to read more though about float-point and rounding errors that may occur.

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    float a = 3.25;

    cout << fixed << setprecision(1) << a;
}
Shadi
  • 1,701
  • 2
  • 14
  • 27