Retain precision with double in Java

前端 未结 22 3148
情歌与酒
情歌与酒 2020-11-21 05:15
public class doublePrecision {
    public static void main(String[] args) {

        double total = 0;
        total += 5.6;
        total += 5.8;
        System.out         


        
22条回答
  •  失恋的感觉
    2020-11-21 05:58

    Do not waste your efford using BigDecimal. In 99.99999% cases you don't need it. java double type is of cource approximate but in almost all cases, it is sufficiently precise. Mind that your have an error at 14th significant digit. This is really negligible!

    To get nice output use:

    System.out.printf("%.2f\n", total);
    

提交回复
热议问题