【问题标题】:Displaying Decimal places using printf method使用 printf 方法显示小数位
【发布时间】:2015-02-25 02:49:24
【问题描述】:

我正在使用 printf 方法进行类似收据的控制台输出。 它列出了项目、价格和数量,然后是总数。

我目前已经按照我想要的方式排列了所有内容,尽管它没有显示 2 个小数位。我需要显示完整的数字,例如:“$1.00”,目前显示的是“$1”。

这就是我所拥有的

    System.out.printf("%-30s %-10s %-10s %-5s", "Item","Quantity","Price","Total\n");
    System.out.printf("%-30s %-10.2f %-10.2s %-5.2s %s", "Gum",gumQuantity,"$"+gumPrice,"$"+gumTotal,"\n");
    System.out.printf("%-30s %-10.2f %-10.2s %-5.2s %s", "Soda",sodaQuantity,"$"+sodaPrice,"$"+sodaTotal,"\n");
    System.out.printf("%-30s %-10.2f %-10.2s %-5.2s %s", "Chips",chipsQuantity,"$"+chipsPrice,"$"+chipsTotal,"\n");
    System.out.printf("%-52s %-5.2s %s", "Subtotal", "$"+subTotal,"\n");
    System.out.printf("%-52s %-5.2s %s", "Sales Tax", "$"+salesTax,"\n");
    System.out.printf("%-52s %-5.2s %s", "Total", "$"+totalFinal,"\n");

输出看起来像这样

    Item                           Quantity   Price      Total
    Gum                            10.00      $1         $1    
    Soda                           3.00       $1         $3    
    Chips                          20.00      $1         $2    
    Subtotal                                             $4    
    Sales Tax                                            $3    
    Total                                                $4   

我怎样才能让它显示完整的值?

【问题讨论】:

    标签: java format printf


    【解决方案1】:

    您可以在第一个参数中添加美元符号,因为目前您正尝试将 String 的小数添加为 %-10.2s 而不是这个,您可以尝试以下方式。如果您的价格是 Integer/String,那么您应该转换它到doubleDouble.valueOf(gumPrice)

    例如:

    System.out.printf("$%-10.2f",12.7);//Pass double/float istead of String
                                  ^
                                  price
    

    【讨论】:

      【解决方案2】:

      您将价格和总额打印为String,您可以替换:

      System.out.printf("%-30s %-10.2f %-10.2s %-5.2s %s", "Gum",gumQuantity,"$"+gumPrice,"$"+gumTotal,"\n");
      

      类似:

      System.out.printf("%-30s %-10.2f $%-10.2f $%-5.2f %n", "Gum", gumQuantity, gumPrice, gumTotal);
      

      注意:

      1. gumQuantitygumPricegumTotal 应该是 doublefloat 类型,否则您应该将它们转换为相应的类型并将它们传递给 printf 方法。
      2. 美元符号现在位于格式化字符串中。

      【讨论】:

        猜你喜欢
        • 2015-03-29
        • 2022-11-18
        • 2011-06-14
        • 1970-01-01
        • 2020-09-13
        • 1970-01-01
        • 2021-04-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多