floating-pointc++-cliroundingprecisionvisual-c++-2015

How to round float number? C++/CLI - VS2015


Suppose there are two float numbers: a, b. I need to assign value of a to b. Then b would be converted to a text string by a function, which I can not change. Convertion is done by taking first 3 decimal digits of a float number without rounding, other points are ignored. This leads to loss of accuracy.

Question: how can I change value of a so, that then after convertion b would be like if it was rounded?

Hope that I managed to explain problem, but if didn`t, please, tell me.


Solution

  • I think that these function use "truncate": 1.2346 => 1.234, right?

    You can add 0.0005

    b = a + 0.0005
    

    Example:

    Round to lower

    a = 1.2341;
    b = a + 0.0005; // 1.2346
    string result = yourfunction(b); // 1.234
    

    Round to upper

    a = 1.2346;
    b = a + 0.0005; // 1.2351
    string result = yourfunction(b); // 1.235