-1

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,071
  • 4
  • 15
  • 29
Sanket Singh
  • 61
  • 1
  • 2
  • 11

2 Answers2

2

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,071
  • 4
  • 15
  • 29
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,611
  • 2
  • 13
  • 26