How to display BigDecimal number with trailing zero in a JSON (not as string)?

前端 未结 2 1172
盖世英雄少女心
盖世英雄少女心 2021-01-14 18:21

In my representation response I have one field which is of BigDecimal type. Its value is 2.30 but the json response display it as 2.3 Is there any way to show also the trail

2条回答
  •  一生所求
    2021-01-14 18:28

    If you want to keep the JSON holding a numeric value, you don't have the choice, a numeric isn't impacted by the traling "0" in a decimal part, so they won't be used. Simply because :

    2.3 = 2.30
    2.3 = 2.300000
    

    The zeros are simply ignored. If you really need to get a value like 2.30, you have two choices,

    1. use a String to hold the formatted number in the JSON
    2. format the value on the client side.

    Both solution will used the same logic :

    String.format("%.2f", 2.3); //String: 2.30
    

    The difference is the moment you format the value.

    Note:

    Since you have a "version" field, I would use a String since a version is represented by numeric value separated by .. See the maven repo of Jackson :

    
    
        com.fasterxml.jackson.core
        jackson-core
        2.9.4
    
    

    2.9.4 is not a number.

提交回复
热议问题