所以我需要计算一个值。
我得到的输入是这样的:
a is seed/m2. The value might a for example 56 but it might be 56.7 also.
b is in g's. for instance 600g
c is % value, might be 90.6 also
d is % value, might be 90.6 also
我得到的结果应该是 kg/ha
常规 int 不会削减它。 (56 * 600/100/100)/100
的值
将为 0.0336
。我可以将它乘以 10000,但我会失去精度。
我也为此尝试了 BigDecimal,但它给了我一个 ArithmeticException: “Non-terminating decimal expansion;当我将 % 变量的值更改为 100 以外的其他值时,没有精确可表示的小数结果”
。
最好的选择是什么?计算在 exel 中很容易进行,因为它知道如何自动转换每个值,但在 Java 代码中进行计算是另一回事。
我的解决方案:
完整版本:
int a = Integer.decode(germinativeSeed.getText().toString());
int b = Integer.decode(seedMass.getText().toString());
int c = Integer.decode(clean.getText().toString());
int d = Integer.decode(germinative.getText().toString());
int result2 = ( a * b / c / d) / 100;
结果为 0
BigDecimal 解决方案:
BigDecimal result2;
BigDecimal a = new BigDecimal(germinativeSeed.getText().toString());
BigDecimal b = new BigDecimal(seedMass.getText().toString());
BigDecimal c;
BigDecimal d;
if (clean.getText().toString().equals("")) {
c = new BigDecimal("100");
} else {
c = new BigDecimal(clean.getText().toString());
}
if (germinative.getText().toString().equals("")) {
d = new BigDecimal("100");
} else {
d = new BigDecimal(germinative.getText().toString());
}
BigDecimal hundred = new BigDecimal("100");
BigDecimal test = new BigDecimal("10000");
result2 = a.multiply(b);
result2 = result2.divide(c, 2, RoundingMode.HALF_UP);
result2 = result2.divide(d, 2, RoundingMode.HALF_UP);
result2 = result2.divide(hundred, 2, RoundingMode.HALF_UP);
result2 = result2.multiply(test);
只有当 % 值为 100% 时,结果才是正确的。
最佳答案
double seed = (double) seedInput;
double m2 = (double) m2Input;
double b = (double) bInput; // unit 'g' is not relevant
double c = (double) cInput;
double d = (double) dInput;
double a = seed / m2;
int result2 = ( a * b / c / d) / 100.0;
所以我将所有内容都转换为 double,这样您就不会在隐式转换为 int 时遇到问题。
关于java - 计算时我的数字使用什么类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29557715/