简体   繁体   English

改变双回合的方式

[英]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 我查看了一下,发现加倍数(按百分比计算)为以下数字: 85.53178390026166

Apparently my program rounded this number up to 86. 显然,我的程序将此数字四舍五入为86。

Now my question is: Is there any way I can stop the program rounding doubles up unless it is .75 or closer? 现在我的问题是:有什么方法可以阻止程序舍入加倍,除非它是0.75或更小? and instead in this example round-down to 85? 而是在此示例中向下舍入到85?

Well first of all notice that 85.53 is CLOSER to 86 than it is to 85 . 首先,要注意的是85.5386更接近85 That being said, if you want it to only round up if it's .75 or greater, do: 话虽如此,如果您只想将其取整为.75或更大,请执行以下操作:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM