【java技巧】Java四舍五入保留小数点后两位

在日常开发中,我们会遇到很多数字处理,最常见的其实就是数值的四舍五入和保留两位小数,在此,我总结5中方法以供参考。

方法1:

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

说明:
​ #.00 表示两位小数 #.0000四位小数 以此类推…

方法2:

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 属性含义为为四舍五入

方法3:

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

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

方法4:

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

说明:
​ 最后乘积的0.01d表示小数点后保留的位数(四舍五入),0.0001 为小数点后保留4位,以此类推…

方法5:

将程序中的double值精确到小数点后两位。可以四舍五入,也可以直接截断。
比如:输入12345.6789,输出可以是12345.68也可以是12345.67。至于是否需要四舍五入,可以通过参数来决定(RoundingMode.UP/RoundingMode.DOWN等参数)。

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));
   }
}

你可能感兴趣的:(JAVA工具类,java,开发语言,jvm)