【发布时间】:2017-12-06 13:50:30
【问题描述】:
我必须创建一个具有 2 个输入参数的函数:
Time duration 在 BigDecimal 中(精度 38,小数位数 6)
和
TimeUnitsType enum(天、小时、分钟或秒)。
结果我需要得到long 值(毫秒);
据我了解,BigDecimal 中的 longValue() 方法在这里无法精确工作,因为它将比例设置为 0,longValueExact() 将抛出 ArithmeticException("Overflow")(因为精度 - 比例 > 19)
public static long convertTimeToMillis(BigDecimal time, TimeUnitsType timeUnitsType) {
long timeLong = time.longValue();
switch (timeUnitsType) {
case DAYS:
return TimeUnit.DAYS.toMillis(timeLong);
case HOURS:
return TimeUnit.HOURS.toMillis(timeLong);
case MINUTES:
return TimeUnit.MINUTES.toMillis(timeLong);
default:
return TimeUnit.SECONDS.toMillis(timeLong);
}
}
所以我需要对每种情况分别进行单独计算。你能帮我么? BigDecimal 操作让我有点害怕,因为我之前没有使用过它们 :) 并且在其余任务中需要精度。
附: Java版本是1.6
【问题讨论】:
-
请准确定义
BigDecimal time所代表的内容。time的持续时间是timeUnitsType的单位还是time在它自己的单位中并被转换为timeUnitsType中的等效持续时间?
标签: java converter long-integer bigdecimal duration