我在格式化程序中的输出格式时遇到麻烦

时间:2019-01-11 21:38:57

标签: java formatting currency

代码格式不正确

起初,当我想要1.00时,代码会吐出1.0。因此,我使用了if语句来解决该问题。然后,代码将给出.5而不是.50,因此我尝试了相同的解决方案,但是没有用。我想知道是否可以制作一个格式化程序,如果小数点右边只有一个数字来解决问题,我是否可以添加一个额外的0。

fan_out

.5而不是.50

1 个答案:

答案 0 :(得分:0)

在您的特定情况下(您的方法返回字符串),一种实现方法是通过使用@ {@ Taslim}的String#format()方法,它会像这样:

public static String dollarAmount(int quarters2, int dimes2, int nickels2, int pennies2) {
    double total = (quarters2 * .25) + (dimes2 * .10) + (nickels2 * .05) + (pennies2 * .01);
    return String.format("Total: $%.2f", total);
}

另一种方法是利用@Jens已经提到的DecimalFormat#format()方法,它会像这样:

public static String dollarAmount(int quarters2, int dimes2, int nickels2, int pennies2) {
    double total = (quarters2 * .25) + (dimes2 * .10) + (nickels2 * .05) + (pennies2 * .01);
    DecimalFormat df = new DecimalFormat(".##", DecimalFormatSymbols.getInstance(Locale.US));
    return "Total: $" + df.format(total);
}

使用您在DecimalFormat变量初始化中看到的DecimalFormatSymbols.getInstance(Locale.US),以便以特定国家/地区的数字格式显示数字值。

对于较小的值,执行此操作的另一种较长的方法是同时使用Math#pow()Math#round()方法,如下所示:

public static String dollarAmount(int quarters2, int dimes2, int nickels2, int pennies2) {
    double total = (quarters2 * .25) + (dimes2 * .10) + (nickels2 * .05) + (pennies2 * .01);

    long factor = (long) Math.pow(10, 2); // 2 is the decimal places
    total = total * factor;
    long tmp = Math.round(total);
    return "Total: $" + String.valueOf((double) tmp / factor);
}

对于更大,更复杂的值,您可能希望使用BigDecimal#setScale()方法来实现,该方法在使用Float或进行计算时可以提供更高的准确性 双重数据类型值(which are inaccurate)....类似这样:

public static String dollarAmount(int quarters2, int dimes2, int nickels2, int pennies2) {
    double total = (quarters2 * .25) + (dimes2 * .10) + (nickels2 * .05) + (pennies2 * .01);

    BigDecimal bd = new BigDecimal(total);
    // The 2 used below is the decimal places. You can
    // use whatever rounding mode you want.
    bd = bd.setScale(2, RoundingMode.HALF_UP); 
    return "Total: $" + String.valueOf(bd.doubleValue());

}

选择;)

相关问题