4

I have this program that resembles a fight and each attack does a random damage amount from a range of two numbers, eg., an attack can do damage from 60ish to 70ish. I say 'ish' because everytime I display the damage amount, it gives a really big decimal number like 70.28326772002643.

I want to know how to make it so that it still displays decimals, but much less, like 70.28. How do I do this?

This is not a duplicate because the other question has python syntax, and I want to know how to do it in Java.

Also, it is not a duplicate because my type is a double, not a float.

  • Check out `System.out.printf` as well as the mentioned `format` specifier documentation. – WJS Nov 27 '19 at 20:37
  • The contributor does not seem to want to print out the value (As your comments above have answers for), they want to store it in a decimal. So, its a duplicate of [Show Only Two Digit After Decimal](https://stackoverflow.com/questions/10959424/show-only-two-digit-after-decimal) – Thomas Rokicki Nov 27 '19 at 21:35
  • @ThomasRokicki Which itself is a duplicate of a duplicate of a duplicate. – user207421 Mar 06 '20 at 23:59

4 Answers4

0

The following will do the trick for you:

public class Main {
    public static void main(String[] args) {
        double d1=70.28326772002643;
        double d1rounded=Math.round(d1 * 100.0) / 100.0;
        System.out.println(d1rounded);

        double d2=70.28726772002643;
        double d2rounded=Math.round(d2 * 100.0) / 100.0;
        System.out.println(d2rounded);
    }
}

Output:

70.28
70.29

I also recommend you check How to round a number to n decimal places in Java for some better ways.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
0

Let's say your output is double output = 70.28326772002643;

Do,

DecimalFormat deci = new DecimalFormat("#.00");

double newOutput = deci.format(output);

newOutput will be equal to 70.28

spinyBabbler
  • 392
  • 5
  • 19
0

Use the printf method, or String.format:

> double d = 1.23456;
> System.out.printf("%.2f\n", d);
1.23

> System.out.printf("%.3f\n", d);
1.235

> String.format("%.2f", d);
"1.23" (String)
> String.format("%.3f", d);
"1.235" (String)
kaya3
  • 47,440
  • 4
  • 68
  • 97
-1

round() function can convert from double to integer, you can multiply 100 and then divide 100 to get 2 decimal place.

    double pi = Math.PI;
    double pi_round = 0.01* Math.round(pi * 100);
    System.out.println(pi_round);
Ryo
  • 1
  • 1
  • 3