0

My problem is, that when you call my round function it works in theory, but in practice it just has some data-lags and I don't want to cut the number with build-ins because I wanted to create a function without build-ins. For example the input round.round(24.754537, 3) doesn't return 24.755 as it should, but it returns 24.75500000000727.

public class Round {
    public double round(double number, int decimals) {
        //Stores the number in rounded number for subtraction below
        double rounded_num = number;
        //Defines the size in which we are rounding
        double round_size = 1d / pow(10, decimals);
        //Subtracts as long as the value is higher or lower than the half round size cuz of rounding till .5
        if (number > 0) {
            while (rounded_num >= round_size/2) {
                rounded_num -= round_size;
            }
        }
        else if (number < 0) {
            while (rounded_num <= -round_size /2) {
                rounded_num += round_size; } }
        //subtracts from the rest of subtracting from the incoming number
        return number - rounded_num;
    }
    
    private int pow(int base, int power) {
        int number = 1;
        for (int i = 0; i < power; i++) {
            number *= base;
        }
        return number;
    }
}
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
xRodn
  • 1

0 Answers0