如何在 Java 中对数字进行自定义四舍五入? [英] How to do custom rounding of numbers in Java?

查看:33
本文介绍了如何在 Java 中对数字进行自定义四舍五入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想对 尾数 大于 0.3 'up' 的数字和低于 0.3 的数字进行舍入'下'.

Suppose I want to round numbers that have mantissa greater than 0.3 'up' and those below 'down'.

我如何用 Java 实现?

How can I do it in Java?

我唯一想到的是Math.round(),但我似乎无法让它遵循某个规则.

The only thing that came to my mind was Math.round(), but I can't seem to make it follow a certain rule.

推荐答案

Math.floor(x+0.7) 应该这样做.

这应该适用于任意尾数.只需将下一个整数的偏移量添加到您的值并向下取整.舍入是按楼层完成的.这是 Java API 对地板说的话:

This should work for an arbitrary mantissa. Just add the offset to the next integer to your value and round down. The rounding is done by floor. Here is what the java API says to floor:

返回最大(最接近正无穷大)双精度值小于或等于参数并且等于数学整数.

Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer.

这个解决方案类似于@Thomas Stets 的解决方案,但恕我直言,它更容易理解,因为只在一个方向上进行了舍入.

This solution is similar to the one from @Thomas Stets, but imho it is easier to understand since rounding is done in only one direction.

这篇关于如何在 Java 中对数字进行自定义四舍五入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆