Reputation: 20555
I have a lot of data which i retrieve from the database and create a chart using those data (some of them are added)
One of the charts is displaying percentage and therefore i have to calculate my data to percent.
My boss has another program that also displays the percentage (but has no graph) and after making my program he came to me and said that the numbers in my table are wrong.
I looked it over my and found that the double (that is calculated into percentage) was the following number: 85.53178390026166
Apparently my program rounded this number up to 86.
Now my question is: Is there any way I can stop the program rounding doubles up unless it is .75 or closer? and instead in this example round-down to 85?
Upvotes: 0
Views: 137
Reputation: 28578
Try this:
int returnRoundOffNumber(Double number)
{
if((number-Integer.parseInt(number)>0.75)
return Math.ceil(number);
else
return Math.floor(number);
}
Upvotes: 1
Reputation: 11310
try this
import java.math.BigDecimal;
BigDecimal myDec = new BigDecimal( myDouble );
myDec = myDec.setScale( 2, BigDecimal.ROUND_HALF_UP );
import java.math.BigDecimal;
BigDecimal myDec = new BigDecimal( myDouble );
myDec = myDec.setScale( 2, BigDecimal.ROUND_HALF_DOWN );
Upvotes: 2
Reputation: 32323
Well first of all notice that 85.53
is CLOSER to 86
than it is to 85
. That being said, if you want it to only round up if it's .75
or greater, do:
Math.floor(number + .25);
Example:
10.2 -> 10.45 -> 10
10.6 -> 10.85 -> 10
10.74 -> 10.99 -> 10
10.76 -> 11.01 -> 11
Upvotes: 3
Reputation: 32391
If your boss is that picky then I suggest you don't round them, but you could rather display the number using a number of fraction digits that you negotiate yo your boss.
Upvotes: 0