四舍五入到最接近的0.05值的问题

问题描述

| 已经有很多关于此的问题。 一个流行的答案是使用以下公式。
  Math.ceiling(myValue * 20) / 20
我需要以下输出作为相应的输入。
     16.489 (input)   - 16.49(output)
使用上面的公式
     16.489*20  = 329.78

     Math.ceil(329.78) = 330.0

     and 330.0 /20  = 16.5 
但我想要的是16.49。 理想情况下,Math.ceil值应为329.8 那么如何解决上述情况呢?还有许多其他类似的情况。     

解决方法

        而不是用2 * 10乘/除,而应使用102。 但是,建议您使用
Math.round(100*a) / 100.0
,或者如果需要打印时使用
printf
DecimalFormat
。 例子:
double input = 16.489;

// Math.round
System.out.println(Math.round(100 * input) / 100.0);

// Decimal format
System.out.println(new DecimalFormat(\"#.##\").format(input));

// printf
System.out.printf(\"%.2f\",input);
输出:
16.49
16.49
16.49
    ,        为什么不使用Math.round()  格式化您的价值? 编辑:Math.round(value * 100.0)/ 100.0;     ,        我认为这将对您有所帮助。此链接为您提供了有关如何将数字四舍五入到小数点后第n位的讨论。     ,        将16.489向上舍入到最接近的0.05正确是16.5,其中16.45是下一个可能的最小值。 看到的行为是正确的。如果要舍入到最接近的0.01,则
Math.ceiling(myValue * 100) / 100
将是一个更合适的解决方案。     ,        尝试这个
round(16.489,2,BigDecimal.ROUND_CEILING);

public static double round(double x,int scale,int roundingMethod) {
        try {
            return (new BigDecimal
                   (Double.toString(x))
                   .setScale(scale,roundingMethod))
                   .doubleValue();
        } catch (NumberFormatException ex) {
            if (Double.isInfinite(x)) {
                return x;
            } else {
                return Double.NaN;
            }
        }
    }
    

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...