-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Description
(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.