0

After Rounding to two decimal places, i alwayse get the same value

float TestT =round(t*100)/100;

enter image description here

i would like to round it and fix it to two decimal places: 0.009999 -> 0.01

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
medbsl
  • 9
  • 5
  • 2
    Please note that often, `float` numbers cannot be represented exactly in binary... – Damien Mar 03 '21 at 13:13
  • 3
    In which case a `float`, just like an `int` is the wrong type for this job. If you need exact 2 decimal places, then one way is to use an integral type, and insert the decimal point at the point of presentation. Or use a *decimal* type from an appropriate library. Boost has one, for example. – Bathsheba Mar 03 '21 at 13:15

1 Answers1

-1

You can do this in 2 steps:-

Step1:- transform your float value to string and use the inbuilt QString feature to perform the rounding for you

Eg:-

  1. @QString::number( 99.48, 'f', 2);
  2. In your case:- QString TestS =QString::number( t, 'f', 2);

Step2:- transform your rounded string value to float Eg:-

  1. in your case :- float TestT= TestS.toFloat()

More info about this here is some links:- QString":http://qt-project.org/doc/qt-5.0/qtcore/qstring.html#number-2 may help you.

Dharman
  • 30,962
  • 25
  • 85
  • 135
  • This has no advantage over the solution of OP, which is right. What is wrong is the assumption that 0.01 can be represented exactly as a `float`: it cannot. – prapin Mar 03 '21 at 15:19