简体   繁体   中英

Big Decimal formatting after rounding

I am having an issue with Big Decimal and its formatting after rounding. I have an input price as 35.90 and the output returns 35.9

This is how I am doing my rounding:

BigDecimal scaledResult = rs.getPrice().setScale(2, BigDecimal.ROUND_HALF_UP);
sc.setPrice(scaledResult);

which returns the 35.9 output even though I have set the scale to two decimal places. Any ideas?

Thanks guys for your help, here is how I have solved it by writing a serializer:

public class BigDecimalSerializer extends JsonSerializer<BigDecimal> {
    @Override
    public void serialize(BigDecimal value, JsonGenerator jgen, SerializerProvider provider) throws IOException,
            JsonProcessingException {
        jgen.writeString(value.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
    }
}

and fields of my model:

@JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal price;

Your rounding is working fine . The reason why you are not getting trailing zeros is that you are returning the response as BigDecimal , instead you need to return as String (as mentioned by others as well).

There is simple way of doing it using @JsonFormat annotation with shape as STRING on top of your BigDecimal variables in your Response Object. Refer below:

 import com.fasterxml.jackson.annotation.JsonFormat;

  class YourResponseObjectClass {

    @JsonFormat (shape=JsonFormat.Shape.STRING)
    private BigDecimal price;

 }

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