简体   繁体   English

如何围绕数学方程的答案

[英]How to round an answer to a mathematical equation

All- I have an app in which the users inputs data such as the cost of a dinner bill and the tip percentage and the number of people. 全部 - 我有一个应用程序,用户输入数据,如晚餐账单的费用和小费百分比和人数。 The app than takes the numbers and outputs the total bill cost and the amount each person has to pay. 应用程序比数字和输出总帐单成本和每个人必须支付的金额。 I am almost there but when the user inputs numbers that don't work well I get outputs like $23.576 or $34.999999999. 我几乎在那里,但当用户输入不能正常工作的数字时,我得到的输出如$ 23.576或$ 34.999999999。 My question is how do I make the app round the two output answers to two decimal places ($55.349 goes to $55.35)? 我的问题是如何使应用程序围绕两个小数位的两个输出答案(55.349美元到55.35美元)? Thanks in advance! 提前致谢!

String roundTwoDecimals(double d) {
        DecimalFormat formatter = new DecimalFormat("#.##");
        return formatter.format(d);
}

You can use Math.round like so: 您可以像这样使用Math.round

    double data = 55.349; // Your data value of whatever

    int decimalPlaces = 2;
    double roundBase = Math.pow(10, decimalPlaces);
    data = (double)(Math.round(data * roundBase)) / roundBase;
    System.out.println(data); // Prints "55.35"

Keep in mind, however: you should NOT use double when it comes to financial applications. 但请记住:在财务应用程序方面,您不应该使用double。 Since yours appears to be small-scale, you should be fine, however, BigDecimal is much easier to use for purposes like these. 由于你的看起来很小,你应该没问题,但BigDecimal更容易用于这些目的。

How to use BigDecimal: clicky . 如何使用BigDecimal: clicky

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM