简体   繁体   中英

Changing how a double rounds

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?

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

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 );

Try this:

int returnRoundOffNumber(Double number)
{  

if((number-Integer.parseInt(number)>0.75)
 return Math.ceil(number);

else   
  return Math.floor(number);
}

如果您的老板很挑剔,那么我建议您不要四舍五入,而宁愿使用您与老板协商的小数位数显示数字。

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