0

I have the following code:

#include <iostream>
#include <string>
#include <math.h>

using namespace std;


double sysmoroundtoabnt(double value, int digits)
{

    double potencia, valorElevado, auxiliar;
    int parteInteira, parteFracionada;

    potencia = pow(10, abs(digits));
    valorElevado = value * (potencia);
    parteInteira = trunc(valorElevado);

    parteFracionada = trunc(modf(valorElevado, &auxiliar) * 100);

    return parteFracionada;

}

int main()
{
    cout << sysmoroundtoabnt(1.015, 2);
}

I set "1.015" to first param's value. When I'm debbugin, that value was change to "1.0149999999999999".

At this code, I set the integer part of value to parteInteira and the decimal part to parteFracionada. Both as int.

So when I return parteFracionada the result is 49, but it must be 50.

Why it happens and how can I solve it ?

Victor Zanella
  • 105
  • 1
  • 7
  • 1
    I don't think that it is the same situation of http://stackoverflow.com/questions/588004/is-floating-point-math-broken, because I want to know how can i solve this problem. – Victor Zanella Sep 26 '16 at 14:39
  • It explains the problem. If you want accurate values, you need to use an accurate representation. Floating point representations will be inaccurate in this case, so you should choose another representation (e.g. fixed point values). In addition `trunc` is the incorrect operation here; you should be using `round`, which would have 'corrected' this issue. – Anya Shenanigans Sep 26 '16 at 14:50
  • There is no general solution. Look for answers on the linked question (don't just look at the most popular answer) that try to fix the problem; decide whether any of them is good for you. – anatolyg Sep 26 '16 at 15:44
  • The problem is that I have to build a new Round function based on ABNT (Associação Brasileira de Normas Técnicas) rules. This is the reaseon that i don't use Round. I don't know any other type that can replace `Double/Float8`. It work well in Pascal – Victor Zanella Sep 26 '16 at 16:48

0 Answers0