控制小数精度(java)

生成double类型随机数

random()函数源码

/**
     * Creates a new random number generator. This constructor sets
     * the seed of the random number generator to a value very likely
     * to be distinct from any other invocation of this constructor.
     */
    public Random() {
    
    
        this(seedUniquifier() ^ System.nanoTime());
    }

nextDouble()函数源码

public double nextDouble() {
    
    
        return (((long)(next(26)) << 27) + next(27)) * DOUBLE_UNIT;
    }

我们可以这样生成一个doublel类型随机数。

代码

import java.util.Random;
public class Format {
    
    
	 public static void main(String[] args) {
    
    
			//方法1
			Random random=new Random();
			double num=random.nextDouble();
			//方法2
			//double num= Math.random(); 
		    System.out.println(num);
	    }
}

输出:

0.04342853133845903

我们发现输出结果是一个[0,1)之间的很长的小数值。如果我们需要这么长的小数位数应该怎么处理呢?

控制小数位数

1.截断 多余小数位

    public class Format {
    
    
        public static void main(String[] args) {
    
    
            double d = 1.23456789;
            // 需要几位小数,就乘以10的几次方,再强转。
            int i = (int) (d * 100000);//注意等式右边带了两个()
            // 又转回去。
            double d2 = (double) i / 100000;//等式右边必须加(double)并且i/10000不要加括号
            System.out.println(d2);
        }
    }

输出

1.23456

2.利用数字格式化

import java.text.NumberFormat;
public class Format {
    
    
	public static void main(String[] args) {
    
    

		double d = 1.23456789;
		NumberFormat Nformat = NumberFormat.getInstance();
		// 设置小数位数。
		Nformat.setMaximumFractionDigits(2);
		// 对d进行转换。
		String str = Nformat.format(d);
		// 将String类型转化位double
		//方法1
		//Double num = Double.parseDouble(str);
		//方法2
		double num=Double.valueOf(str).doubleValue();
		System.out.println(num);
	}
}

输出:

1.23457

3.利用十进制格式化器

import java.text.DecimalFormat;
public class Format {
    
    
	public static void main(String[] args) {
    
    
        double d = 1.23456789;
        // 设置格式样式
        DecimalFormat Dformat=new DecimalFormat("0.00000");
        // 格式化
        String str=Dformat.format(d);
		//将String类型转化位double
		//Double num = Double.parseDouble(str);//方法1
		double num=Double.valueOf(str).doubleValue();//方法2
		System.out.println(num);
	}
}

输出

1.23457

4.利用BigDecimal(终极)

  1. BigDecimal是java.math包中提供的API类,可处理超过16位有效位的数。在开发中,如果我们需要精确计算的结果,则必须使用BigDecimal类来操作。
  2. BigDecimal所创建的是对象,故我们不能使用传统的+、-、*、/等算术运算符直接对其对象进行数学运算,而必须调用其相对应的方法。方法中的参数也必须是BigDecimal的对象。构造器是类的特殊方法,专门用来创建对象,特别是带有参数的对象。
import java.math.BigDecimal;
public class Format {
    
    
	public static void main(String[] args) {
    
    

        double d = 1.23456789;
        BigDecimal decimal=new BigDecimal(d);
        // 四舍五入为五位小数
        double d2=decimal.setScale(5,BigDecimal.ROUND_HALF_UP).doubleValue();
        System.out.println(d2);
	}
}

输出:

1.23457

参考资料:

Java控制小数位,获得随机数
BigDecimal详解
Java字符串和数字间的转换

猜你喜欢

转载自blog.csdn.net/qq_41571459/article/details/113009687
今日推荐