您现在的位置是:首页 >精选问答 > 2024-05-19 17:20:39 来源:
double类型数据(double类型)
大家好,我是小夏,我来为大家解答以上问题。double类型数据,double类型很多人还不知道,现在让我们一起来看看吧!
展开全部
double类型直接进行运算会出现精度问题,可先转换为字符串之后再进行运算。
import java.math.BigDecimal;
public class Arith {
// 默认除法运算精度
private static final int DEF_DIV_SCALE = 10;
// 这个类不能实例化
private Arith() {
}
public static double add(double v1, double v2)
{
BigDecimal b1 = new
BigDecimal(Double.toString(v1));
BigDecimal b2 = new
BigDecimal(Double.toString(v2));
return
b1.add(b2).doubleValue();
}
public static double sub(double v1, double v2)
{
BigDecimal b1 = new
BigDecimal(Double.toString(v1));
BigDecimal b2 = new
BigDecimal(Double.toString(v2));
return
b1.subtract(b2).doubleValue();
}
public static double mul(double v1, double v2)
{
BigDecimal b1 = new
BigDecimal(Double.toString(v1));
BigDecimal b2 = new
BigDecimal(Double.toString(v2));
return
b1.multiply(b2).doubleValue();
}
public static double div(double v1, double v2) {
return
div(v1, v2, DEF_DIV_SCALE);
}
public static double div(double v1, double v2, int scale)
{
if (scale < 0) {
throw new
IllegalArgumentException(
"The
scale must be a
positive integer or
zero");
}
BigDecimal b1 = new
BigDecimal(Double.toString(v1));
BigDecimal b2 = new
BigDecimal(Double.toString(v2));
return b1.divide(b2, scale,
BigDecimal.ROUND_HALF_UP).doubleValue();
}
public static double round(double v, int scale) {
if
(scale < 0) {
throw new
IllegalArgumentException(
"The
scale must be a
positive integer or
zero");
}
BigDecimal b = new
BigDecimal(Double.toString(v));
BigDecimal one = new
BigDecimal("1");
return b.divide(one, scale,
BigDecimal.ROUND_HALF_UP).doubleValue();
}
}
public class test {
public static void main(String[] args)
{
double d1=0.2;
double d2=0.1;
double
d3=d1+d2;
System.out.println(Arith.add(d1,
d2));
System.out.println(Arith.sub(d1,
d2));
System.out.println(d3);
}
}
本文到此讲解完毕了,希望对大家有帮助。