IBM / JSONata4Java

Open Source Java version of JSONata
Apache License 2.0
88 stars 36 forks source link

Support hexadecimal, octal and binary numbers in $number() #305

Closed sagIoTPower closed 2 months ago

sagIoTPower commented 2 months ago

Hi,

I would like to use the $number() function to decode some hexadecimal numbers.

The current implementation does not support this, e.g. $number('0x575') throws an exception: com.api.jsonata4java.expressions.EvaluateRuntimeException: Unable to cast value to a number: "0x575"

The JSONata $number() function supports this and returns 1397.

Would it be possible to add some code like the following to the current implementation in NumberUtils.java:

public static int convertToInteger(String number) {
        if (number.startsWith("0x")) {
            // Hexadecimal number
            return Integer.parseInt(number.substring(2), 16);
        } else if (number.startsWith("0o")) {
            // Octal number
            return Integer.parseInt(number.substring(2), 8);
        } else if (number.startsWith("0b")) {
            // Binary number
            return Integer.parseInt(number.substring(2), 2);
        } else {
            // Decimal number or invalid format
            return Integer.parseInt(number);
        }
    }
wnm3 commented 2 months ago

Thanks for the idea. I've pushed a new version to Maven Central 2.4.9 and it should be available in a few hours (it is 4/21 1:21pm ET now). If you agree the issue is resolved please close it. Thanks -- it gave me an opportunity to update the pom.xml for newer libraries.

sagIoTPower commented 2 months ago

I tested the new version 2.4.9 and it works. So you can close the issue. Thank you.