Search code examples
coldfusioninteger-divisioncoldfusion-2016

ColdFusion too big to be an integer


I am trying to convert a large number going in to Megabytes. I don't want decimals

numeric function formatMB(required numeric num) output="false" {
    return arguments.num \ 1024 \ 1024;
    } 

It then throws an error

enter image description here

How do I get around this?


Solution

  • You can't change the size of a Long, which is what CF uses for integers. So you'll need to BigInteger instead:

    numeric function formatMB(required numeric num) {
        var numberAsBigInteger = createObject("java", "java.math.BigInteger").init(javacast("string", num));
        var mbAsBytes = 1024 ^ 2;
        var mbAsBytesAsBigInteger = createObject("java", "java.math.BigInteger").init(javacast("string", mbAsBytes));
        var numberInMb = numberAsBigInteger.divide(mbAsBytesAsBigInteger);
        return numberInMb.longValue();
    }
    
    CLI.writeLn(formatMB(2147483648));
    

    But as Leigh points out... for what you're doing, you're probably better off just doing this:

    return floor(arguments.num / (1024 * 1024));