I am unable to format decimals and I am unsure why.

Discussion in 'Plugin Development' started by AoH_Ruthless, Mar 18, 2014.

Not open for further replies.
1. Offline

AoH_Ruthless

I am trying to get a double and then damage the player using the double. Here is my code:

Code:
```double chance = (10 * (radius - 2)) / (radius) / 9; //Although it doesn't make a difference, 'radius' is an integer.

DecimalFormat df = new DecimalFormat("#.##");
chance = Double.valueOf(df.format(chance));
System.out.println(chance);```
Doing the math, 'chance' should be a value of 0.79 (Substituting 7 for radius) but instead it prints out 0.0. I thought it might be because the value starts with 0. So I added 1 to my algorithm for originally getting chance and now it printed out 1.0.

Clearly, it's truncating the double. How do I fix it so that it doesn't truncate?

#1
2. Offline

The rounding is happening because you're doing an integer division. When you divide two integers together, the result is an integer before you even do anything with it.
Code:java
`System.out.println( 10 / 3 );System.out.println( 10 / 3.0 );System.out.println( 10 / (float)3 );`
Code:
```3
3.3334
3.3334```
Always cast the denominator (bottom one) to a float or double before doing a division.

#2
jthort likes this.