Java四舍五入时保留指定小数位数

方式一:

double f = 3.1516;
BigDecimal b = new BigDecimal(f);
double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); 
输出结果f1为 3.15;

源码解读:
  public BigDecimal setScale(int newScale, int roundingMode) //int newScale 为小数点后保留的位数, int roundingMode 为变量进行取舍的方式;
  BigDecimal.ROUND_HALF_UP 属性含义为为四舍五入java

方式二:

String format = new DecimalFormat("#.0000").format(3.1415926);
System.out.println(format);
输出结果为 3.1416

解读:
  #.00 表示两位小数 #.0000四位小数 以此类推…git

方式三:

double num = 3.1415926;
String result = String.format("%.4f", num);
System.out.println(result);
输出结果为:3.1416

解读:
  %.2f 中 %. 表示 小数点前任意位数 2 表示两位小数 格式后的结果为f 表示浮点型。spa

方式四:

double num = Math.round(5.2544555 * 100) * 0.01d;
System.out.println(num);
输出结果为:5.25

解读:
  最后乘积的0.01d表示小数点后保留的位数(四舍五入),0.0001 为小数点后保留4位,以此类推......code

方式五:

1. 功能

将程序中的double值精确到小数点后两位。能够四舍五入,也能够直接截断。
好比:输入12345.6789,输出能够是12345.68也能够是12345.67。至因而否须要四舍五入,能够经过参数来决定(RoundingMode.UP/RoundingMode.DOWN等参数)。orm

2. 实现代码

package com.clzhang.sample;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class DoubleTest {
    /** 保留两位小数,四舍五入的一个老土的方法 */
    public static double formatDouble1(double d) {
        return (double)Math.round(d*100)/100;
    }
    public static double formatDouble2(double d) {
        // 旧方法,已经再也不推荐使用
    // BigDecimal bg = new BigDecimal(d).setScale(2, BigDecimal.ROUND_HALF_UP);
        // 新方法,若是不须要四舍五入,能够使用RoundingMode.DOWN
        BigDecimal bg = new BigDecimal(d).setScale(2, RoundingMode.UP);
        return bg.doubleValue();
    }
    public static String formatDouble3(double d) {
        NumberFormat nf = NumberFormat.getNumberInstance();

        // 保留两位小数
        nf.setMaximumFractionDigits(2); 
        // 若是不须要四舍五入,能够使用RoundingMode.DOWN
        nf.setRoundingMode(RoundingMode.UP);
        return nf.format(d);
    }
    /**这个方法挺简单的 */
    public static String formatDouble4(double d) {
        DecimalFormat df = new DecimalFormat("#.00");
        return df.format(d);
    }
    /**若是只是用于程序中的格式化数值而后输出,那么这个方法仍是挺方便的, 应该是这样使用:System.out.println(String.format("%.2f", d));*/
    public static String formatDouble5(double d) {
        return String.format("%.2f", d);
    }
    public static void main(String[] args) {
        double d = 12345.67890;
        System.out.println(formatDouble1(d));
        System.out.println(formatDouble2(d));
        System.out.println(formatDouble3(d));
        System.out.println(formatDouble4(d));
        System.out.println(formatDouble5(d));
    }
}

 

3. 输出

12345.68
12345.68
12,345.68
12345.68
12345.68blog

相关文章
相关标签/搜索