简体   繁体   中英

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. My question is how do I make the app round the two output answers to two decimal places ($55.349 goes to $55.35)? Thanks in advance!

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

You can use Math.round like so:

    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. Since yours appears to be small-scale, you should be fine, however, BigDecimal is much easier to use for purposes like these.

How to use BigDecimal: clicky .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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