Java四舍五入

方法1:

String result;
DecimalFormat df = new DecimalFormat("0.0"); //保留一位小数
df.setRoundingMode(RoundingMode.HALF_UP);
result = df.format(0.14);
System.out.println(result);
result = df.format(0.15);
System.out.println(result);
result = df.format(0.16);
System.out.println(result);

result = df.format(0.24);
System.out.println(result);
result = df.format(0.25);
System.out.println(result);
result = df.format(0.26);
System.out.println(result);

result = df.format(0.34);
System.out.println(result);
result = df.format(0.35);
System.out.println(result);
result = df.format(0.36);
System.out.println(result);

输出结果:

0.1
0.1
0.2
0.2
0.3
0.3
0.3
0.3
0.4

RoundingMode.HALF_UP的注释说明是,被舍弃的小数大于5是,才进位,否则舍弃掉,因此这种算法是,五舍六入的。
源码:

        /**
         * Rounding mode to round towards {@literal "nearest neighbor"}
         * unless both neighbors are equidistant, in which case round up.
         * Behaves as for {@code RoundingMode.UP} if the discarded
         * fraction is ≥ 0.5; otherwise, behaves as for
         * {@code RoundingMode.DOWN}.  Note that this is the rounding
         * mode commonly taught at school.
         *
         *<p>Example:
         *<table border>
         * <caption><b>Rounding mode HALF_UP Examplesb>caption>
         *<tr valign=top><th>Input Numberth>
         *<th>Input rounded to one digit<br> with {@code HALF_UP} rounding
         *<tr align=right><td>5.5td>  <td>6td>
         *<tr align=right><td>2.5td>  <td>3td>
         *<tr align=right><td>1.6td>  <td>2td>
         *<tr align=right><td>1.1td>  <td>1td>
         *<tr align=right><td>1.0td>  <td>1td>
         *<tr align=right><td>-1.0td> <td>-1td>
         *<tr align=right><td>-1.1td> <td>-1td>
         *<tr align=right><td>-1.6td> <td>-2td>
         *<tr align=right><td>-2.5td> <td>-3td>
         *<tr align=right><td>-5.5td> <td>-6td>
         *table>
         */
    HALF_UP(BigDecimal.ROUND_HALF_UP),

算法2:

/**
     * 四舍五入
     * @param d      数字
     * @param scale  保留小数点位数
     * @return
     */
    public static double roundNumber(double d, int scale) {
        int n = 1, s = 0;
        while(s < scale) {
            n *= 10;
            s ++;
        }

        double result = (double)Math.round(d*n) / n;
        return result;
    }

你可能感兴趣的:(Java,EE,java,算法)