2

I'm having problems with my game with fluctuating values ​​and can not round the decimal values. I tried even this function:

const double dbShift = pow (10.0, 5);
return floor (pValor * dbShift + 0.5) / dbShift;

This function can run "floor (pValor * dbShift + 0.5)" correctly. However the divide by dbShift again, happens again the same problem.

In my game, for example, I have a double to save the tempoDecorrido in milliseconds (5337, for example). When trying to convert in seconds (5337 / 1000.0f), the return value always brings an unnecessary amount of decimal places (5.3369999999999997 instead of 5337).

This causes major problems multiply when floating by other values ​​such as position and rotation vectors.

I searched on google and there are several sites that explain the cause of the problem, but none that have the solution thereof, unless u want to display the value on the screen as a string, but this is not the case. I need to work with floating values, not with information on the screen.

Finally, someone in a definitive solution to this. Force floating values ​​to have five decimal places, for example?

Recalling that already test the above function without success. Already, I appreciate the help.

  • 1
    Floating point values are not 'real' values, and you will drive yourself mad trying to treat them as such. See [Bruce Dawson's floating-point series](https://randomascii.wordpress.com/category/floating-point/) and [Is floating point math deterministic?](http://blogs.msdn.com/b/shawnhar/archive/2009/03/25/is-floating-point-math-deterministic.aspx) – Chuck Walbourn Nov 02 '15 at 21:53
  • Maybe this will help: [What Every Computer Scientist Should Know About Floating Point](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html). – Thomas Matthews Nov 02 '15 at 21:53
  • What 'major problems'? Can you explain one, (apart from FP compares failing)? – Martin James Nov 02 '15 at 21:53
  • 1
    if you only need five decimal places, go fixed point and use a sufficiently large integer type with a gain of 100000. – user4581301 Nov 02 '15 at 21:54
  • "Force floating values ​​to have five decimal places" - 1. that is not possible with C++, you'd have to write your own library. 2. ... and you'll have the exact same problem. Only a few digits sooner. – Jongware Nov 02 '15 at 21:54
  • No measurement apparatus in existence has the precision you already have. Yet you ask for more. It seems you're blaming the precision for some other, undisclosed problem. – Cheers and hth. - Alf Nov 02 '15 at 21:57
  • Remember that the internal accuracy and representation can be different than the displayed version. If you only need 5 digits printed, keep the extra internal accuracy and study the `std::setprecision` modifier. – Thomas Matthews Nov 02 '15 at 22:01

0 Answers0