java精度控制_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 Double();
/
/⽅法2
//double num= Math.random();
System.out.println(num);
}
}
输出:
0.04342853133845903
我们发现输出结果是⼀个[0,1)之间的很长的⼩数值。如果我们不需要这么长的⼩数位数应该怎么处理呢?
控制⼩数位数
1.截断 多余⼩数位
public class Format {
// 需要⼏位⼩数,就乘以10的⼏次⽅,再强转。
int i = (int) (d * 100000);//注意等式右边带了两个()
// ⼜转回去。
double d2 = (double) i / 100000;//等式右边必须加(double)并且i/10000不要加括号System.out.println(d2);
}java生成随机数的方法
}
输出
1.23456
2.利⽤数字格式化
NumberFormat;
public class Format {
public static void main(String[] args) {
double d = 1.23456789;
NumberFormat Nformat = Instance();
// 设置⼩数位数。
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.利⽤⼗进制格式化器
DecimalFormat;
public class Format {
// 设置格式样式
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(终极)
BigDecimal是java.math包中提供的API类,可处理超过16位有效位的数。在开发中,如果我们需要精确计算的结果,则必须使⽤BigDecimal类来操作。
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字符串和数字间的转换