1

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!

4

2 に答える 2

3
String roundTwoDecimals(double d) {
        DecimalFormat formatter = new DecimalFormat("#.##");
        return formatter.format(d);
}
于 2012-06-20T23:58:03.607 に答える
1

あなたは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"

ただし、覚えておいてください。金融アプリケーションに関しては、doubleを使用しないでください。あなたは小規模に見えるので、あなたは大丈夫なはずですが、BigDecimalこのような目的のためにはるかに使いやすいです。

BigDecimalの使用方法:clicky

于 2012-06-20T23:56:57.383 に答える