So, assuming, for some reason, floats are absolutely required in the programme one is creating despite the inaccuracy regarding decimal points, is there any method one can use to round them to 2 decimal places without converting them into doubles?
            Asked
            
        
        
            Active
            
        
            Viewed 317 times
        
    -1
            
            
        - 
                    What's wrong with Math.round()? If you just need to display it, you can use format. – clinomaniac Dec 21 '17 at 17:51
- 
                    Don’t round the float data. Just limit the number of places when you format it as a string. – VGR Dec 21 '17 at 17:53
- 
                    Isn't that only used for doubles? I know I could convert the floats into doubles, but my programme is mostly composed of floats (I'm following from a textbook and the author decided to use floats because at my current level rounding isn't required). (for clinomaniac). – SilentEevee Dec 21 '17 at 17:57
- 
                    (to VGR) I'm not formatting it further. I've already done the necessary calculations with it, all is left is the rounding. – SilentEevee Dec 21 '17 at 18:02
1 Answers
0
            
            
        Try this:
public static float roundFloat(float number, int scale)
{
    int pow = 10;
    for (int i = 1; i < scale; ++i)
        pow *= 10;
    float tmp = number * pow;
    return ( (float) ( (int) ((tmp - (int) tmp) >= 0.5f ? tmp + 1 : tmp) ) ) / pow;
}
Solid and fast.
 
    
    
        Tommaso Belluzzo
        
- 23,232
- 8
- 74
- 98
 
    