【问题标题】:How to set DecimalFormat for a program to 2 decimal places in Java如何在 Java 中将程序的 DecimalFormat 设置为 2 位小数
【发布时间】:2014-03-02 23:51:33
【问题描述】:

我正在尝试制作的程序需要在程序运行后将双倍“收入”设置为小数点后 2 位。
下面显示了我设置的方式,但是在我运行程序之后,它仍然要么掉零要么结束。可能是什么问题?

    println("Please enter your filing status");
    println("Enter 0 for single filers,");
    println("      1 for married filing jointly,");
    println("      2 for married filing seperately,");
    println("      3 for head of household");
    int status = readInt("Status: ");
    double income = readDouble("Please enter your taxable income: ");
    DecimalFormat df = new DecimalFormat("#.00");
    System.out.print(df.format(income));

if ((status == 0) && (income <= SINGLE_BRACKET1))
    {
        println("You owe: $" + (income * .1));
    }
else if  ((status == 0) && (income <= SINGLE_BRACKET2))
    {
        println("You owe: $" + ((SINGLE_BRACKET1 * .1) + 
                (income - SINGLE_BRACKET1) * .15));

    }

【问题讨论】:

    标签: java decimal decimalformat


    【解决方案1】:

    不确定我是否理解您的问题,但您必须格式化每个输出:

            println("You owe: $" + df.format(income * .1));
    

            println(String.format("You owe: $%.2f", income * .1));
    

    【讨论】:

    • 只要您使用美元符号就可以使用,与语言环境无关的方法是使用 NumberFormat.getCurrencyInstance()
    【解决方案2】:

    使用pattern 强制格式保留两位小数:

    DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance();
    df.setMaximumFractionalPlaces(2);
    df.format(income);
    

    或者,您可能需要查看currency formatter,因为您正在格式化货币值。

    【讨论】:

    • 现在它告诉不兼容的类型在 getInstance 之后突出显示 () 任何想法
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    • 2022-06-23
    相关资源
    最近更新 更多