spring boot注解 对double保留两位小数

全局设置

public class CustomerDoubleSerialize extends JsonSerializer {
    private DecimalFormat df = new DecimalFormat("0.00");

    @Override
    public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if(o.toString() != null && !"-".equals(o)) {
            Double dd=Double.parseDouble(o.toString());

            jsonGenerator.writeString(df.format(dd));

        } else{
            jsonGenerator.writeString(o.toString());

        }
    }
}

在需要使用的实体字段上加上注解即可。@JsonSerialize(using = CustomerDoubleSerialize.class)

实体类加上注解。

@Data
public class SalesVolumeVo {

@JsonSerialize(using = CustomerDoubleSerialize.class)
private String salesVolume1;

}

以下是一个简单的使用Spring Boot编写的流速和流量计算器,其中流速和流量都保留2位小数: ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @RestController public class FlowCalculatorApp { public static void main(String[] args) { SpringApplication.run(FlowCalculatorApp.class, args); } @GetMapping("/flow/{volume}/{time}") public double calculateFlow(@PathVariable double volume, @PathVariable double time) { double flow = volume / time; return Math.round(flow * 100.0) / 100.0; // 保留2位小数 } @GetMapping("/velocity/{distance}/{time}") public double calculateVelocity(@PathVariable double distance, @PathVariable double time) { double velocity = distance / time; return Math.round(velocity * 100.0) / 100.0; // 保留2位小数 } } ``` 在上面的代码中,我们使用了Spring Boot注解@SpringBootApplication来启用自动配置,并使用@RestController注解来定义一个RESTful API。我们定义了两个GET请求方法,分别用于计算流量和流速。这两个方法都接受两个路径变量volume和time(或distance和time),分别代表体积(或距离)和时间。在方法中,我们根据公式计算出流量或流速,并使用Math.round方法将结果保留两位小数。最后,我们将结果作为方法的返回值。 我们可以使用浏览器或命令行工具(如curl)来测试这些API。例如,我们可以使用以下命令来计算流量: ``` curl http://localhost:8080/flow/1000/10 ``` 这将返回一个保留两位小数的浮点数,表示每秒流动的体积。类似地,我们可以使用以下命令来计算流速: ``` curl http://localhost:8080/velocity/1000/10 ``` 这将返回一个保留两位小数的浮点数,表示每秒移动的距离。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值