alibaba / fastjson

FASTJSON 2.0.x has been released, faster and more secure, recommend you upgrade.
https://github.com/alibaba/fastjson2/wiki/fastjson_1_upgrade_cn
Apache License 2.0
25.74k stars 6.5k forks source link

format number #2943

Open huifer opened 4 years ago

huifer commented 4 years ago
        System.out.printf("%.2f", 1.323);

console1.32

I use @JSONField(format = "%.2f") for Double &String &Float& BigDecimal


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.math.BigDecimal;

@Data
@NoArgsConstructor
public class RunTest {

    @JSONField(format = "%.2f")
    private Double d0;
    @JSONField(format = "%.2f")
    private String d1;
    @JSONField(format = "%.2f")
    private Float d2;
    @JSONField(format = "%.2f")
    private BigDecimal d3;

    public static void main(String[] args) {
        System.out.printf("%.2f", 1.323);
        RunTest runTest = JSON.parseObject("{\n" +
                "  \"d0\": 1.323,\n" +
                "  \"d1\":1.323,\n" +
                "  \"d2\": 1.323,\n" +
                "  \"d3\":1.323\n" +
                "}", RunTest.class);
    }

}

I hope value is 1.32 What should I do?

Licker05 commented 4 years ago

maybe don't have the method ,you can try to use deserializeUsing and write your own deserialize class