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

Vin*_*C M 4 java double decimal rounding

已经有很多问题要问这个问题了.

一个流行的答案是使用以下公式.

  Math.ceiling(myValue * 20) / 20
Run Code Online (Sandbox Code Playgroud)

我需要以下输出作为相应的输入.

     16.489 (input)   - 16.49(output)
Run Code Online (Sandbox Code Playgroud)

使用上面的公式

     16.489*20  = 329.78

     Math.ceil(329.78) = 330.0

     and 330.0 /20  = 16.5 
Run Code Online (Sandbox Code Playgroud)

但我想要的是16.49.

理想情况下,Math.ceil的东西应该给出329.8

那么我们如何解决上述问题呢?还有许多类似的案例.

aio*_*obe 5

而不是乘以/除以2*10,你应该用10 2.

但是,我建议您使用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);
Run Code Online (Sandbox Code Playgroud)

输出:

16.49
16.49
16.49
Run Code Online (Sandbox Code Playgroud)