package com.itheima_01;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class Demo03 {
public static void main(String[] args) {
/*
保留指定小数点后位数
*/
double a = 1.0123456789123456789;
//方法一:最简单的方法,调用DecimalFormat类
//指定保留小数点后几位
DecimalFormat df = new DecimalFormat(".0000000000");
//转换
String str = df.format(a);
//String转double
double v = Double.parseDouble(str);
System.out.println(v);
//方法二:直接通过String类的format实现
String str2 = String.format("%.10f", a);
double v2 = Double.parseDouble(str2);
System.out.println(v2);
//方法三:通过BigDecimal实现
BigDecimal bd = new BigDecimal(a);
double v1 = bd.setScale(11, BigDecimal.ROUND_HALF_UP).doubleValue();
System.out.println(v1);
//方法四:通过NumberFormat类实现
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(12);
String s = nf.format(a);
double v3 = Double.parseDouble(s);
System.out.println(v3);
}
}
Original: https://www.cnblogs.com/exmyth/p/16188869.html
Author: 牧之丨
Title: java 保留小数点后指定位数四种方法
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/537431/
转载文章受原作者版权保护。转载请注明原作者出处!