Home > Back-end >  Integer multiplication acting strange
Integer multiplication acting strange

Time:03-30

Im writing a fraction class where I want to convert a double to a fraction. I do this by increasing the double by a scaling factor of 10 until it's a whole number and then putting that scaling factor as the denominator of the fraction

My problem is that the scaling factor, which is an integer, should only be multiples of 10, such as 100 or 10000, but I get back values crazy far away from it.

public static Fraction ToFraction(double number)
{
    Fraction fraction = new Fraction();
    double tempNumber = number;
    int multiplier = 1;

    //Makes decimal to whole number and then sets the scaling to be the denominator
    //1.03 => 10.3 => 103 thus fraction = 103/100
    while (!(tempNumber % 1 == 0))
    {
        tempNumber *= 10;
        multiplier *= 10;
    }

    fraction.numerator = ((long)tempNumber);
    fraction.denominator = multiplier;

    return fraction;
}

Ive attempted to make a fraction with 0.5154812884, as a test, meaning that I should get the fraction 5,154,812,884 / 10,000,000,000 but instead it returns 5,154,812,884/1,410,065,408

I tried searching but I couldn't find anyone with similar issues

Ive included some pictures from debugging where it shows the input double and the resulting numerator (numerator) and denominator (multiplier) Number used for testing

Resulting fraction where tempNumber is right but multiplier is wrong

CodePudding user response:

I believe your issue is that your denominator is a 32-bit integer. This would make sense as 10,000,000,000 overflows in a 32-bit int and will return a result of about 1,410,065,412. Consider changing this.

double tempNumber = number;
long multiplier = 1;

Edit: The denominator result you received I was also able to receive in testing and changing multiplier (used to determine denominator) to a long fixed it for me.

  • Related