Search code examples
c#unity-game-enginebigintegerbigint

C# / Unity: Multiply BigInteger by Float


I have a BigInteger cost = 111111222222333333444444555555 and a float costMultiply 1.1f.

I try to:

newCost = cost * costMultiply

And get an "Operator "*" cannot be applied"- Error.

I also tried:

int multiplierBuffer = (int)(costMultiply * 10);
cost = cost * (multiplierBuffer / 10);

This does not throw an error but gives back the initial cost value (not multiplied by 1.1f).

How do I multiply my BigInteger by a float?


Solution

  • You will have to cast your BigInteger to a double/Double.

        BigInteger cost = new BigInteger(10000000000000000000);
        float costMultiply = 1.1f;
        double dCost = (double) cost;
        double result = dCost * costMultiply;
        // And since you want a BigInteger at the end
        BigInteger bigIntResult = new BigInteger(result);
    

    The actual type of result would be Double because the integer can't fit into a double. C# takes care of that for you.

    This can obviously be simplified.

        BigInteger cost = new BigInteger(10000000000000000000);
        float costMultiply = 1.1f;
        BigInteger bigIntResult = new BigInteger((double) cost * costMultiply);
    

    The thing is, your mathematics is going to be a screwy because of the varying levels of precision in the data types. I wouldn't use this approach if you need precision. However, since you want to multiply an integer by a floating point number and get an integer result, I guess you won't be bothered by precision issues.