java 保留小数点后指定位数四种方法


1
package com.itheima_01; 2 3 import java.math.BigDecimal; 4 import java.text.DecimalFormat; 5 import java.text.NumberFormat; 6 7 public class Demo03 { 8 public static void main(String[] args) { 9 /* 10 保留指定小数点后位数 11 */ 12 double a = 1.0123456789123456789; 13 //方法一:最简单的方法,调用DecimalFormat类 14 //指定保留小数点后几位 15 DecimalFormat df = new DecimalFormat(".0000000000"); 16 //转换 17 String str = df.format(a); 18 //String转double 19 double v = Double.parseDouble(str); 20 System.out.println(v); 21 22 //方法二:直接通过String类的format实现 24 String str2 = String.format("%.10f", a); 25 double v2 = Double.parseDouble(str2); 26 System.out.println(v2); 27 //方法三:通过BigDecimal实现 28 BigDecimal bd = new BigDecimal(a); 29 double v1 = bd.setScale(11, BigDecimal.ROUND_HALF_UP).doubleValue(); 30 System.out.println(v1); 31 32 //方法四:通过NumberFormat类实现 33 NumberFormat nf = NumberFormat.getNumberInstance(); 34 nf.setMaximumFractionDigits(12); 35 String s = nf.format(a); 36 double v3 = Double.parseDouble(s); 37 System.out.println(v3); 38 39 40 } 41 }

 

posted @ 2020-10-21 11:12  厚我  阅读(2352)  评论(0编辑  收藏  举报