4种方法,都是四舍五入,例,保留4位小数:
import java.math.BigDecimal; import java.text.DecimalFormat; import java.text.NumberFormat; public class Format { static double f = 111231.55856666666; public static void m1() { BigDecimal bg = new BigDecimal(f); double f1 = bg.setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue(); System.out.println(f1); } /** * DecimalFormat转换最简便 */ public static void m2() { DecimalFormat df = new DecimalFormat("#.0000"); System.out.println(df.format(f)); } /** * String.format打印最简便 */ public static void m3() { System.out.println(String.format("%.4f", f)); } public static void m4() { NumberFormat nf = NumberFormat.getNumberInstance(); nf.setMaximumFractionDigits(4); System.out.println(nf.format(f)); } public static void main(String[] args) { Format.m1(); Format.m2(); Format.m3(); Format.m4(); } }
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/10931.html