You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
37 lines
1.1 KiB
Java
37 lines
1.1 KiB
Java
|
1 month ago
|
package com.example.pdaplccontrol;
|
||
|
|
|
||
|
|
import java.math.BigDecimal;
|
||
|
|
|
||
|
|
final class WeightInputParser {
|
||
|
|
|
||
|
|
private static final BigDecimal GRAMS_PER_KG = new BigDecimal("1000");
|
||
|
|
|
||
|
|
private WeightInputParser() {
|
||
|
|
}
|
||
|
|
|
||
|
|
static short kgToGrams(String input) {
|
||
|
|
if (input == null || input.trim().isEmpty()) {
|
||
|
|
throw new IllegalArgumentException("请输入重量");
|
||
|
|
}
|
||
|
|
|
||
|
|
BigDecimal kg;
|
||
|
|
try {
|
||
|
|
kg = new BigDecimal(input.trim());
|
||
|
|
} catch (NumberFormatException e) {
|
||
|
|
throw new IllegalArgumentException("重量格式不正确");
|
||
|
|
}
|
||
|
|
|
||
|
|
BigDecimal grams = kg.movePointRight(3).stripTrailingZeros();
|
||
|
|
if (kg.compareTo(BigDecimal.ZERO) < 0
|
||
|
|
|| grams.compareTo(BigDecimal.valueOf(PlcConfig.MAX_WEIGHT_GRAMS)) > 0) {
|
||
|
|
throw new IllegalArgumentException("重量范围为 0-30kg");
|
||
|
|
}
|
||
|
|
|
||
|
|
try {
|
||
|
|
return grams.shortValueExact();
|
||
|
|
} catch (ArithmeticException e) {
|
||
|
|
throw new IllegalArgumentException("重量最多精确到 0.001kg");
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|