ColdFusion too big to be an integer

天涯浪子 提交于 2019-12-19 05:53:13

问题


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

How do I get around this?


回答1:


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));



回答2:


the size of a Long, which is what CF uses for integers

Small correction for those that may not read the comments. CF primarily uses 32 bit signed Integers, not Long (which has a much greater capacity). So as the error message indicates, the size limit here is the capacity of an Integer:

  • Integer.MAX_VALUE = 2147483647
  • Long.MAX_VALUE = 9223372036854775807

It is worth noting that although CF is relatively typeless, some Math and Date functions also have the same limitation. For example, although DateAdd technically supports milliseconds, if you try and use a very large number:

//  getTime() - returns number of milliseconds since January 1, 1970 
currentDate = dateAdd("l", now().getTime(), createDate(1970,1,1));

... it will fail with the exact same error because the "number" parameter must be an integer. So take note if the documentation mentions an "Integer" is expected. It does not just mean a "number" or "numeric" ...



来源:https://stackoverflow.com/questions/35593313/coldfusion-too-big-to-be-an-integer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!