我正在做一项大学作业,我用替身来赚钱。我知道使用doubles作为货币价值是不可取的,所以我想知道如何用BigDecimal替换我现有的具有doubles的代码。
由于这是一项大学作业,我不想在我的代码上获得直接帮助,也不想在这里发布它,所以我创建了以下代码,我希望得到直接回复,例如更改我提供的代码,以便我可以理解发生了什么。
我想知道如何用整型或双精度乘/除/加/减BigDecimal,或者这是不可能的。
还有其他关于BigDecimal用法的主题,但它们没有涵盖我的具体问题,但是,如果我忽略了一个已经被回答的帖子,我道歉。
代码如下:
import java.util.Scanner;
import java.text.NumberFormat;
class example {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
NumberFormat fm = NumberFormat.getCurrencyInstance();
System.out.println("Enter the first amount:");
double money1 = in.nextDouble();
System.out.println("Enter the second amount:");
double money2 = in.nextDouble();
System.out.println("Enter the third amount:");
double money3 = in.nextDouble();
double tax = 0.2;
double totalmoney = money1 + money2 + money3;
double moneytax = (totalmoney)*tax;
System.out.println("Your money added together is: " + fm.format(totalmoney));
System.out.println("Tax on your money is: " + fm.format(moneytax));
System.out.println("Your money after tax deduction is: " + fm.format((totalmoney-moneytax)));
}
}发布于 2011-12-26 05:46:15
BigDecimal的另一种选择可能是使用长整型以美分为单位进行所有计算,并在末尾插入小数点。
发布于 2011-12-25 20:12:09
如果你想避免使用double,你需要从一开始就不使用它。
BigDecimal money1 = new BigDecimal(in.nextLine());您应该能够看到四舍五入后的结果完全相同。
发布于 2011-12-25 19:59:44
BigDecimals是不可变的,但您可以使用特定的调用创建新的are:
BigDecimal two = new BigDecimal("2.00");
BigDecimal four = new BigDecimal("4.00");
BigDecimal result = four.divide(two);您可能还想看看scale()方法。
https://stackoverflow.com/questions/8629475
复制相似问题