首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >动态计算找零到最接近的10美元

动态计算找零到最接近的10美元
EN

Stack Overflow用户
提问于 2013-10-17 00:11:11
回答 4查看 330关注 0票数 0

我是Java新手,我正在尝试弄清楚如何动态地计算到最接近10美元的零头。例如,用户输入一个值(34.36),然后我的代码就会计算账单的小费、税金和总金额(总计44.24)。如果没有用户输入,我需要从$50.00开始计算变化。我试图从44.24四舍五入到50.00,但没有运气,显然我做错了什么。我已经尝试了Math.round,并尝试使用%查找剩余部分。任何关于如何获得由于最近的10美元价值的总变化的帮助将是很大的。提前谢谢你,下面是我的代码: Full dis-closer,这是一个作业项目。

代码语言:javascript
复制
import java.util.Scanner; 
import java.text.NumberFormat;
import java.lang.Math.*;

public class test1
{
public static void main(String[] args)
{
    Scanner sc = new Scanner(System.in);
    //Get input from user
    System.out.println("Enter Bill Value:                   ");
    double x = sc.nextDouble();

    //Calculate the total bill
    double salesTax = .0875;
    double tipPercent = .2;
    double taxTotal = (x * salesTax);
    double tipTotal = (x * tipPercent);
    double totalWithTax = (x + taxTotal);
    double totalWithTaxAndTip = (x + taxTotal + tipTotal);

    //TODO:  Test Case 34.36...returns amount due to lower 10 number
    //This is where I am getting stuck                  
    double totalChange = (totalWithTaxAndTip % 10);




    //Format and display the results
    NumberFormat currency = NumberFormat.getCurrencyInstance();
    NumberFormat percent = NumberFormat.getPercentInstance();

    //Build Message / screen output
    String message =
        "Bill Value:                         " + currency.format(x) + "\n" + 
        "Tax Total:                          " + currency.format(taxTotal) + "\n" +
        "Total with Tax:                     " + currency.format(totalWithTax) + "\n" +
        "20 Percent Tip:                     " + currency.format(tipTotal) + "\n" +
        "Total with Tax and 20 Percent Tip:  " + currency.format(totalWithTaxAndTip) + "\n" +
        "Total Change:                       " + currency.format(totalChange) + "\n";

    System.out.println(message);

}
}
EN

回答 4

Stack Overflow用户

发布于 2013-10-17 00:17:24

你让double totalChange = round((totalWithTaxAndTip / 10)) * 10;

票数 1
EN

Stack Overflow用户

发布于 2013-10-17 00:19:00

Math.ceil(double)将向上舍入一个数字。所以你需要的是这样的东西:

代码语言:javascript
复制
 double totalChange = (int) Math.ceil(totalWithTaxAndTip / 10) * 10;

对于totalWithTaxAndTip =44.24时,totalChange = 50.00

对于totalWithTaxAndTip = 40.00,totalChange = 40.00

票数 0
EN

Stack Overflow用户

发布于 2013-10-17 00:21:37

Math.round将一个数字舍入为最接近的整数,因此,正如其他人所示,您需要除以10,然后在舍入后乘以10:

代码语言:javascript
复制
double totalChange = tenderedAmount - totalWithTaxAndTip;

double totalChangeRounded  = 10 * Math.round(totalChange / 10);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19408425

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档