Retain precision with double in Java

前端 未结 22 3149
情歌与酒
情歌与酒 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:59

    As others have noted, not all decimal values can be represented as binary since decimal is based on powers of 10 and binary is based on powers of two.

    If precision matters, use BigDecimal, but if you just want friendly output:

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

    Will give you:

    11.40
    

提交回复
热议问题