Java - rounding by quarter intervals

喜夏-厌秋 提交于 2019-12-24 17:43:06

问题


I'm running into following issue...

Does an already 'built-in' function exists in java to round given random numbers to the closest lower quarter value.

These are the given random numbers:

2.00 -> 2.00
2.24 -> 2.00
2.25 -> 2.25
2.49 -> 2.25
2.50 -> 2.50
2.74 -> 2.50
2.75 -> 2.75
2.99 -> 2.75
3.00 -> 3.00

回答1:


You can multiply the value by 4 then floor it then divide by 4.

public static double quarterRound(double v){
   return Math.floor(v*4)/4;
}



回答2:


You need to round to quarters so:

  • Multiply by 4
  • Floor to next int
  • Divide by 4

Note that if you reliable values it is better to works with BigDecimal instead of primitive values (double or float). The algorithm stay the same.




回答3:


Try this:

double value = 2.99D;
value = (double)(int)(value * 4) / 4;


来源:https://stackoverflow.com/questions/32274898/java-rounding-by-quarter-intervals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!