JAVA保留小数点位数

/**
 * java 如何保留指定位数的小数
 * @author Administrator
 *
 */
public class Test04 {
    public static void main(String[] args) {
        //保留小数点位数
        double pi = 3.1415;
        //四舍五入函数
        System.out.println(Math.round(3.5));
        
        //取值范围小的,和取值范围大的做运算,整个表达式会被提升成大的数据类型
        //掌握这种方法
        System.out.println(pi*1000);
        System.out.println(Math.round(pi*1000)/1000.0);//结果为3.142
//Math.round(a)为四舍五入方法
DecimalFormat df
= new DecimalFormat(".000"); String str = df.format(pi); //String 转化为doouble double result2 = Double.parseDouble(str); System.out.println(result2); //String str转换为double String str2 = String.format("%.3f", pi); double results = Double.parseDouble(str2); System.out.println(results); BigDecimal bd = new BigDecimal(pi); double result4 = bd.setScale(3,BigDecimal.ROUND_HALF_UP).doubleValue(); System.out.println(result4); } }
原文地址:https://www.cnblogs.com/MRCH/p/11643721.html