如何在小数点后将小数舍入到2位(Java)

Use*_*ser 1 java decimal number-formatting

我是java的新手,我必须创建这个程序,我不知道从哪里开始.有人可以帮助我做什么以及如何编写代码来开始?

编写一个模拟收银机的程序.提示用户输入三个项目的价格.将它们添加到一起以获得小计.确定小计的税(6%).查找销售小计加税的总金额.显示每个项目的价格,小计金额,税额和最终金额.

到目前为止我有这个:

package register;
import java.util.Scanner;

public class Register {

    public static void main(String[] args) {

        Scanner price = new Scanner(System.in);

        System.out.print("Please enter a price for item uno $");
        double priceuno = price.nextDouble();

        System.out.print("Please enter a price for item dos $" );
        double pricedos = price.nextDouble();

        System.out.print("Please enter a price for item tres $");
        double pricetres = price.nextDouble();

        double total = ((priceuno) + (pricedos) + (pricetres));
        System.out.println("The subtotal is $" + total);

        double tax = .06;

        double totalwotax = (total * tax );
        System.out.println("The tax for the subtotal is $" + totalwotax);
        double totalandtax = (total + totalwotax);
        System.out.println("The total for your bill with tax is $" + totalandtax);

    }
}
Run Code Online (Sandbox Code Playgroud)

输出(如果价格让我们说price1 = 1.65,price2 = 2.82和price3 = $ 9.08)看起来像这样:

请购买第一项$ 1.65的价格

请输入第二项$ 2.82的价格

请输入第3项$ 9.08的价格

小计是13.55美元

小计的税金是0.8130000000000001

您的税收账单总额为14.363000000000001

如何将小计和总帐单的税额四舍五入到小数点后的小数点后两位?

谢谢

Bla*_*ood 6

对于像这样的事情,Java有一个DecimalFormat类.

http://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html

所以你想要添加到你的代码中

 DecimalFormat df = new DecimalFormat("###,##0.00");
Run Code Online (Sandbox Code Playgroud)

并将输出更改为

 double totalwotax = (total * tax );
 System.out.println("The tax for the subtotal is $" + df.format(totalwotax));
 double totalandtax = (total + totalwotax);
 System.out.println("The total for your bill with tax is $" + df.format(totalandtax));
Run Code Online (Sandbox Code Playgroud)

这将确保您的分数的小数点右侧正好有两位数字,并且如果总数低于1美元,则至少保留一位数字.如果它是1000或以上,它将使用逗号在正确的位置格式化.如果您的总数高于100万,您可能需要将其改为这样的东西以获得额外的指挥官

DecimalFormat df = new DecimalFormat("###,###,##0.00");
Run Code Online (Sandbox Code Playgroud)

编辑: 所以Java也内置支持格式化货币.忘记DecimalFormatter并使用以下内容:

NumberFormat nf = NumberFormat.getCurrencyInstance();
Run Code Online (Sandbox Code Playgroud)

然后像使用DecimalFormatter一样使用它,但没有前面的美元符号(它将由格式化程序添加)

System.out.println("The total for your bill with tax is " + nf.format(totalandtax));
Run Code Online (Sandbox Code Playgroud)

此外,这种方法是区域敏感的,所以如果你在美国它将使用美元,如果在日本它使用日元,等等.


Ker*_*nic 5

用户不要用double BigDecimal!

  • 虽然您的陈述是正确的,但将此作为评论发布更为合适. (2认同)
  • @ZouZou哦,对不起,我的坏))btw漂亮的徽标在你的页面上 (2认同)
  • @ informatik01尽管如此,你是对的.请Marko Frelih等待有足够的代表发布此评论而不是答案 (2认同)