开发者

Java rounding by specific step

开发者 https://www.devze.com 2023-03-19 00:10 出处:网络
Frequently we need to round a number like an amount for minimum currency granularity like 0.05. I faced an overflow problem in Java, and have seemingly solved it...would like you to review if it\'s a

Frequently we need to round a number like an amount for minimum currency granularity like 0.05.

I faced an overflow problem in Java, and have seemingly solved it...would like you to review if it's a correct solution...there are other solutions present on this forum as well...

public static float round(float input, float step) {

float a = Math.round(input / step) * step;

//Can't return "a" directly because of overflow problem in some cases
int b = Math.round(a * 100);

return (float) (float)b / 100f; }

But this will only work for 2 decimal place step (like 0.05开发者_StackOverflow) as I am hard coding 100 here...


This will work for any step size:

public static float round(float input, float step) 
{
  return ((Math.round(input / step)) * step);
}


If you work with hundreds of decimals, float is not the type you need. May I redirect you to BigDecimal?

0

精彩评论

暂无评论...
验证码 换一张
取 消