我有一个带有双参数的构造函数,它需要保留 6 位十进制数。为了将数字转换为(分子,分母)格式,它将数字传递给另一个接受长参数的函数。
// A double value (6 decimal will be used)
public DoubleToLong(double d)
{
System.out.println("Double is " + d); // Double is 9.2233720368547E13
convert((long) (d * 1000000), 1000000);
}
public void convert(long num, long den)
{
System.out.println("Numerator: " + num + " Denominator: " + den); // Numerator: 9223372036854775807 Denominator: 1000000
}
当 9223372036854L 传递给构造函数时, 分子:9223372036853999616 分母:1000000 ->(确定)
当 92233720368547L 传递给构造函数时, 分子:9223372036854775807 分母:1000000 ->(挪威克朗)
与 1000000 相乘时发生溢出。如何修改构造函数以也使用所有长值。
最佳答案
这里的问题是 long 的最大大小。为了避免这个问题,您需要使用 BigDecimal
但是您还需要重写转换函数才能使用 BigDecimal。
关于java - 将双变量传递给具有长参数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49346131/