There is a well-known method of rounding numbers in a mathematical way, that is, without using any functions and procedures. This method looked something like this:

digit = 3.141527; digit = (digit*100)/100; // округление до сотых 

But it does not work, I forgot ... If someone knows this method, please prompt.

    2 answers 2

    Probably you mean

     digit = 3.141592653589793; digit = ((int)(digit*100 + 0.5))/100.0; // округление до сотых 

    Note that decimal fractions are not quite accurately represented by double values, so you get a result that is slightly different from the mathematically correct one.


    Update:
    for negative caste numbers, int does not work as expected. Corrected taking into account this option:

     digit = ((int)(digit*100 + (digit >= 0 ? 0.5 : -0.5))/100.0; // округление до сотых 
    • And why do you add 0.5 to the fractional chati, which is then trimmed? Maybe there is some sense - I do not shy. - o2n3e
    • 2
      Everything was correctly written by the respondent. If it is not clear to anyone why 0.5 is added, then I will note: the truth is somewhere nearby. - skegg
    • 3
      @ o2n3e: rounding off! (int) (0.1 + 0.5) == 0 (int) (0.8 + 0.5) == 1 - VladD
    • one
      Yes, it is! It turns out that it was necessary to multiply and divide not by an integer (100), but by fractional (100.0) =) - LOLPADT

    Like this

     digit = 3.141527; digit = (int)((digit*100))/100; 
    • @KoVadim: you have the wrong side of castes, you get a floating point division - VladD
    • wrote from the phone :) - KoVadim