Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error in getting string representation of an ObjectNode with a float number value #707

Closed
cowtowncoder opened this issue Feb 16, 2015 · 1 comment
Milestone

Comments

@cowtowncoder
Copy link
Member

(note: moved from FasterXML/jackson-core#179; reported by @navidqar)


Test Case:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

public static void main() {
    final float testValue = 0.45f;
    final ObjectMapper mapper = new ObjectMapper();
    final ObjectNode objectNode = mapper.createObjectNode();
    objectNode.put("Test String", testValue);
    System.out.println(objectNode.toString());
}

Actual output:
{"Test String":0.44999998807907104}

*Expected output: *
{"Test String":0.45}

What causes the problem:
ObjectNode.put creates a com.fasterxml.jackson.databind.node.FloatNode object.
When the conversion to String is requested, FloatNode.toString(value) uses a helper method which is NumberOutput.toString(_value) to convert the float value into its String representation.
There are only three overrides of this helper method and none of them accept a float argument:

public static String toString(double value)
public static String toString(long value)
public static String toString(int value)

So what happens in fact is that an implicit cast between float and double occurs which causes the problem.

Suggested workaround:
To fix the problem, we need to add a toString(float value) method to NumberOutput to properly convert the value of a float to String.
Optionally, we can change the method signatures in NumberOutput to accept boxed classes (Float, Long, Integer, etc.) so that implicit casting is disabled and a compilation error is caused when such an implicit conversion is performed.

@cowtowncoder
Copy link
Member Author

Fixed in 2.3.6 / 2.4.6 / 2.5.2.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant