本文介绍了舍入为偶数的一半的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果可能的话,我需要四舍五入到最接近的0.5.

I need to round to nearest 0.5 if possible.

10.4999 = 10.5

10.4999 = 10.5

以下是快速代码:

import java.text.DecimalFormat;
import java.math.RoundingMode;

public class DecimalFormat
{
   public static void main(String[] args)
   {
      DecimalFormat dFormat = new DecimalFormat("#.0");
      dFormat.setRoundingMode(RoundingMode.HALF_EVEN);

      final double test = 10.4999;

      System.out.println("Format: " + dFormat.format(test));
   }
}

这不起作用,因为6.10000 ...四舍五入到6.1等...需要四舍五入到6.0

This doesn't work because 6.10000... rounds to 6.1 etc...need it to round to 6.0

谢谢您的反馈.

推荐答案

与其尝试四舍五入到最接近的0.5,再将其加倍,四舍五入到最接近的int,然后除以2.

Rather than try rounding to the nearest 0.5, double it, round to the nearest int, then divide by two.

这样,2.49变成4.98,四舍五入到5变成2.5.
2.24变成4.48,四舍五入到4变成2.

This way, 2.49 becomes 4.98, rounds to 5, becomes 2.5.
2.24 becomes 4.48, rounds to 4, becomes 2.

这篇关于舍入为偶数的一半的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 00:42