有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java从不同的双精度数计算

我有一个问题,关于如何从不同的双精度计算

比如说

我有三种类型的双重数据

price (x, y, z)
    1. Double type1 = 1.67876
    2. Double type2 = 129.789
    3.Double type3 = 1278.79

我想用10作为逗号后的2位数的最后一个数字来计算所有的双精度类型 如果逗号后有5位数字,则函数将为

比如说

Double returnX = type1-0.00010;

如果逗号后有3位数字,则函数将

Double returnY = type2-0.010;

如果逗号后有2个数字,则函数将

Double returnY = type3-0.10;

那么,如何为这一点制定逻辑呢


共 (1) 个答案

  1. # 1 楼答案

    它可以这样实现:

    static double reduce(double x) {
        double res = x;
        String s = "" + x;
        int posDot = s.indexOf(".");
        if (posDot > -1) {
            int fractionWidth = s.length() - posDot - 1;
            double reduceAmount = 1;
            while (fractionWidth  > 1) {
                reduceAmount *= 0.1;
            }
            res = x - reduceAmount;
        }
        return res;
    }