The pitfall of interface return type is List<Long>

Table of contents

data loss demo

How to write in controller

@Operation(summary = "通过标签获取表单id")
    @GetMapping("listIdByTag")
    public Result<List<Long>> listIdByTag(@ModelAttribute Query query) {
    
    
        query.setUserId(contextUtil.getUserid());
        return Result.content(demoService.listIdByTag(query));
    }
实际数据:
[1656187461040214016,1650042689615695872,1656188185293623296]
前端接收到是数据:
[1656187461040214000,1650042689615696000,1656188185293623300]

It is obvious that there is a loss of accuracy.

Loss of precision is a common problem when working with numeric data, especially when working with floating point numbers. To avoid loss of precision, string types can be used instead of numeric types when transferring data between the front and back ends.

Specifically, if the interface return type in Spring Boot is List<Long>, it can be converted to List<String>a type, and the value of the string type is converted to the Long type when the front end receives it. For example, you can use the String.valueOf() method in Java to convert the value of Long type to String type, and then use parseInt() or parseFloat() to convert the value of String type to Long when the front end parses the JSON array type.

In addition, if you need to perform calculations with floating point numbers, you can use classes in Java BigDecimalto avoid loss of precision. The BigDecimal class provides high-precision numerical calculations and can handle any number of decimals, thereby avoiding precision problems in floating-point calculations.

Summarize

When dealing with numerical data, it is necessary to select the appropriate data type and calculation method according to the specific scenario to avoid problems such as loss of precision.

Guess you like

Origin blog.csdn.net/zhoqua697/article/details/130638261