Java 按特定步长舍入
我们经常需要对数字进行四舍五入,例如最小货币粒度(例如 0.05)的金额。
我在Java中遇到了溢出问题,并且似乎已经解决了它...希望您检查一下它是否是正确的解决方案...这个论坛上也存在其他解决方案...
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; }
但这仅适用于小数点后两位放置步长(如 0.05),因为我在这里硬编码 100...
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) as I am hard coding 100 here...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这适用于任何步长:
This will work for any step size:
如果您使用数百位小数,则
float
不是您需要的类型。我可以将您重定向到BigDecimal
?If you work with hundreds of decimals,
float
is not the type you need. May I redirect you toBigDecimal
?