开发者社区> 问答> 正文

如何在Java中四舍五入到2.5?

所以我正在为Android制作健身应用,现在我要求用户输入数字,例如72.5

我将使用这个数字并取其百分比,并将函数应用于此等。

我需要确保将这个数字所占的百分比四舍五入为2.5。这是因为在英国体育馆中,您只有以下板块:1.25x2 = 2.5 2.5x2 = 5 5 + 2.5 = 7.5,10、15、20、25

我的意思是,它将是这样的数字:40、42.5、45、47.5、50

如何将数字N舍入到最接近的2.5?我知道math.Round()会四舍五入到最接近的整数,但是这样的自定义数字呢?

问题来源:Stack Overflow

展开
收起
montos 2020-03-22 08:17:45 1238 0
2 条回答
写回答
取消 提交回答
  • 自己实现的话,方法还是很多的,

    例如某个数xxx.y取整数部分xxx,+0.5看是否比这个xxx.y大,即
    xxx.y-xxx.5 > 0就返回xxx+1, 
    xxx.y-xxx.5 == 0就返回xxx.5, 
    xxx.y-xxx.5 < 0就返回xxx
    
    2020-03-22 08:23:40
    赞同 展开评论 打赏
  • 如下进行:

    public class Main {
        public static void main(String args[]) {
            // Tests
            System.out.println(roundToNearest2Point5(12));
            System.out.println(roundToNearest2Point5(14));
            System.out.println(roundToNearest2Point5(13));
            System.out.println(roundToNearest2Point5(11));
        }
    
        static double roundToNearest2Point5(double n) {
            return Math.round(n * 0.4) / 0.4;
        }
    }
    

    输出:

    12.5
    15.0
    12.5
    10.0
    

    说明:

    通过以下示例将更容易理解:

    double n = 20 / 3.0;
    System.out.println(n);
    System.out.println(Math.round(n));
    System.out.println(Math.round(n * 100.0));
    System.out.println(Math.round(n * 100.0) / 100.0);
    

    输出:

    6.666666666666667
    7
    667
    6.67
    

    如您在这里看到的,四舍五入20 / 3.0返回7(这是添加0.5到后的底值20 / 3.0。选中此选项可了解实现)。但是,如果您想将其四舍五入到最接近的小数1/100位(即2小数点后一位),则更简单的方法(但不是那么精确。请检查一下以获取更精确的方法)是四舍五入n * 100.0(这样就可以了667)将其除以100.0得到6.67(即最多2个小数位)。注意1 / (1 / 100.0) = 100.0

    同样,要将数字四舍五入到最接近的2.5位置,则需要对1 / 2.5 = 0.4ie 进行相同的操作Math.round(n * 0.4) / 0.4。

    要将数字四舍五入到最接近的100位置,您将需要对1 / 100 = 0.01ie 进行相同的操作Math.round(n * 0.1) / 0.1。

    要将数字四舍五入到最接近的0.5位置,您将需要对1 / 0.5 = 2.0ie 进行相同的操作Math.round(n * 2.0) / 2.0。

    我希望这很清楚。

    回答来源:Stack Overflow

    2020-03-22 08:19:56
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载