简体   繁体   中英

Jackson Mapper integer from json parsed as double with drong precision

Greeting. I had a working solution, but after making a multiple changes on project it doesn't work anymore.

The problem: Front-end sending integer value 565656 which is an attribute of the object converted by Jackson ObjectMapper . i need to get a double with precision 2 from this integer value.

This is the java model:

public class Item {

    private int condoId;
    private Integer itemId;
    private String owner;

    @NotNull
    @Size(min=1, max=60)
    private String itemTitle;

    @NotNull
    @Size(min=1, max=1000)
    private String itemDescr;

    @NotNull
    @Size(min=1, max=45)
    private String itemEmail;

    @NotNull
    @Size(min=1, max=16)
    private Double itemPrice;
}

Was working before:

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

    *In controller, received a request data as string data*

             ObjectMapper mapper = new ObjectMapper();
             JsonNode node = null;
             node = mapper.readTree(data);
             Item item = mapper.convertValue(node.get("item"), Item.class);
            NumberFormat formatter = new DecimalFormat(".00");
            item.setItemPrice(Double.parseDouble(formatter.format(item.getItemPrice())));

Now this solution giving me wrongly formatted values (like 5.67657654E8 ) from 567657654 . What is the way to convert the received integer attribute to the required double?

PS. in PostgreSQL DB it is stored as numeric(10,2) .

EDIT: probably the right question is - why the received int 567657654 from json POST data is deserialized to double 5.67657654E8 , which is a "solid" 5 + decimal .67657654E8

There is no precision problem here. Every digit of the input appears in the output. You are merely seeing, but not recognizing, scientific notation for floating-point. The reason for that lies on your own code: you have an itemPrice column declared as NUMERIC(10,2) but you have mapped that to a Java Double . This is not correct: it is causing this problem; and it will cause untold others further down the track.

The correct Java type to use for that is not Double , or double , but BigDecimal .

Never use floating-point for money.

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