在保持原始值的同时将 BigDecimal 显示为整数
Displaying BigDecimal as Integer while Keeping Original Value
该程序的目的是提供正确的零钱。例如:
输入:45.54 美元
输出:4 张十美元钞票,
1张五美元钞票,
2个宿舍,
4 便士。
现在开始我的问题:
我想在不丢失原始值的情况下将 BigDecimal 显示为整数,因为我必须一直向下除法,直到我得到 0.01 便士。
我当前的代码如下:
BigDecimal tenDollar = BigDecimal.valueOf(10);
BigDecimal tenDollarNext;
BigDecimal fiveDollar = BigDecimal.valueOf(5);
BigDecimal fiveDollarNext;
/* Get Input From User */
System.out.print("Please enter the amount to be converted: ");
Scanner scan = new Scanner(System.in);
BigDecimal money = scan.nextBigDecimal();
NumberFormat usdFormat = NumberFormat.getCurrencyInstance(Locale.US);
usdFormat.setMinimumFractionDigits(2);
usdFormat.setMaximumFractionDigits(2);
System.out.println("Amount you entered: " + usdFormat.format(money));
/* Begin Processing and Displaying Information */
tenDollarNext = money.divide(tenDollar);
System.out.println(tenDollarNext + " Ten Dollar Bills");
fiveDollarNext = tenDollarNext.divide(fiveDollar, 0, RoundingMode.FLOOR);
System.out.println(fiveDollarNext + " Five Dollar Bills");
最终显示:
Please enter the amount to be converted: 45.54
Amount you entered: .54
4.554 Ten Dollar Bills
0 Five Dollar Bills
我的目标是让 4.554 显示为 4 而不会丢失计算末尾的小数位。我确信对此有一个简单的答案,我希望有人可以告诉我它的转换或指出我可以找到答案的方向。 None 我的搜索查询有帮助。
使用 BigDecimal
class 的 divideToIntegralValue
方法代替 divide
。这个returns一个BigDecimal
,它的值是一个整数。然后,您可以从 money
中减去适当的金额并继续。
该程序的目的是提供正确的零钱。例如:
输入:45.54 美元
输出:4 张十美元钞票, 1张五美元钞票, 2个宿舍, 4 便士。
现在开始我的问题:
我想在不丢失原始值的情况下将 BigDecimal 显示为整数,因为我必须一直向下除法,直到我得到 0.01 便士。
我当前的代码如下:
BigDecimal tenDollar = BigDecimal.valueOf(10);
BigDecimal tenDollarNext;
BigDecimal fiveDollar = BigDecimal.valueOf(5);
BigDecimal fiveDollarNext;
/* Get Input From User */
System.out.print("Please enter the amount to be converted: ");
Scanner scan = new Scanner(System.in);
BigDecimal money = scan.nextBigDecimal();
NumberFormat usdFormat = NumberFormat.getCurrencyInstance(Locale.US);
usdFormat.setMinimumFractionDigits(2);
usdFormat.setMaximumFractionDigits(2);
System.out.println("Amount you entered: " + usdFormat.format(money));
/* Begin Processing and Displaying Information */
tenDollarNext = money.divide(tenDollar);
System.out.println(tenDollarNext + " Ten Dollar Bills");
fiveDollarNext = tenDollarNext.divide(fiveDollar, 0, RoundingMode.FLOOR);
System.out.println(fiveDollarNext + " Five Dollar Bills");
最终显示:
Please enter the amount to be converted: 45.54
Amount you entered: .54
4.554 Ten Dollar Bills
0 Five Dollar Bills
我的目标是让 4.554 显示为 4 而不会丢失计算末尾的小数位。我确信对此有一个简单的答案,我希望有人可以告诉我它的转换或指出我可以找到答案的方向。 None 我的搜索查询有帮助。
使用 BigDecimal
class 的 divideToIntegralValue
方法代替 divide
。这个returns一个BigDecimal
,它的值是一个整数。然后,您可以从 money
中减去适当的金额并继续。