projun14
projun14

Reputation: 109

Java serializing an object with primitive float fields to Json

I have an API that looks like this:

@GetMapping("/floattest")
@ResponseBody
public ApiResult getFloatTest() {
    ApiResult result = new ApiResult();
    ApiObject test = new ApiObject(81684436f, 74258578f, 7425858f);
    result.setData(test);
    return result;
}

public class BalanceDetail {
    private float a;
    private float b;
    private float c;
}

API call returns:

{
    "data": {
        "a": 81684432,
        "b": 74258576,
        "c": 7425858
    }
}

I'd appreciate a step-by-step explanation of how these values are turned into completely different values to the client without any warnings.

Upvotes: 0

Views: 318

Answers (1)

eugene-karanda
eugene-karanda

Reputation: 790

It is not a Jackson problem.

If you run this:

public class Main {
    public static void main(String[] args) {
         System.out.println(81684436f);
    }
}

You will get 8.1684432E7.

So, the reason behind this behavior is how floating point works. You can read more on https://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.2.3

Upvotes: 1

Related Questions