0

I need to round the answer 23.428 and get 23.4.

I did a little search about it and I may need to include a line float round (s) but I did it and CODEBLOCKS gives me an error.

Note: the file Information.txt contains numbers 7.5 305.5 4.09 4

My code is:

#include <iostream>
#include <fstream>
#include <cmath>

using namespace std;

int main()
{
   float m, k, kk;
   int n;
   float s;

   ifstream fd("Information.txt");
   fd >> k >> m >> kk >> n;



   k = k / 100;
   m = m * k;
   kk = kk * m;
   s = kk / n;

   /*s=((((k/100)*m)*kk)/n);*/



   fd.close();

   ofstream fr ("Rezults.txt");
   fr << s;
   fr.close();

   return 0;
}
Sofie
  • 3
  • 3
  • 1
    possible duplicate of [Rounding Number to 2 Decimal Places in C](http://stackoverflow.com/questions/1343890/rounding-number-to-2-decimal-places-in-c) – Inisheer Nov 18 '13 at 05:51

2 Answers2

3

You can just multiply the number by 10, round it and then divide by 10 again:

float x = 23.428;
x = std::round(10.0*x);
x /= 10.0;
fatihk
  • 7,789
  • 1
  • 26
  • 48
  • Which in general won't work. The problem is that the question is about displaying base 10 values, while floating-point numbers are typically represented internally as base 2 values. There is no guarantee that you can convert a finite-length base 10 representation into a finite-length base 2 value. For example, `0.1` cannot be represented exactly as a binary value, and any display system that says the binary value is `0.1` is tinkering with the truth. – Pete Becker Nov 18 '13 at 14:14
0

Floating-point values (i.e. floats) usually aren't stored in base 10, but when you display their values they get converted to base 10 because that's what most of us are used to. Output streams (std::cout and the fr in the example) do this conversion, with a default precision of 6 digits. To display 3 digits, just change the precision:

#include <iostream>
#include <iomanip>
#include <fstream>

int main() {
    float num = 23.428;

    std::cout << std::setprecision(3) << num << '\n';

    std::ofstream fr("Rezults.txt");
    fr << std::setprecision(3) << num << '\n';

    return 0;
}
Pete Becker
  • 74,985
  • 8
  • 76
  • 165