简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM