我正在使用Big Deciaml设置json中数据的比例和舍入十进制数。
在json中采样数据:
{"dataMap":{"DATE":"20071.0","mean":"20225.08483315143","ByGroup":"Mean"}
用于设置比例,四舍五入并用新的数字替换原始数字的代码-
//body - JSON body as String
//rndNumber - scale OR digits required after dedcimal
private static String roundDecimalNumbers(def body, int rndNumber)
{
def ids = body =~ /[-+]?[0-9]*\.[0-9]+(?:[eE][-+]?[0-9]+)?/
String number
double dblNumber
BigDecimal dec
double newNumber
(0..<ids.count).each
{
number = ids[it].toString()
dec = new BigDecimal(String.valueOf(number)).setScale(rndNumber, BigDecimal.ROUND_FLOOR).stripTrailingZeros()
body = body.toString().replace(number, dec.toString()) //replacing the orignial number with the scaled and rounded number
}
return body.toString()
}
对于某些十进制数字实例,我遇到如下异常 例如对于上述示例数据,我会出错-
java.lang.AssertionError:data [rowNumber = 4] .dataMap.data [rowNumber = 97] .dataMap.mean 预期:202258483315145获得:202258483315143
其他类似的异常-由a。java.lang.AssertionError引起: data [rowNumber = 2] .dataMap.data [rowNumber = 73] .dataMap.lower1预期: -354402976665825 得到了:-354402976665821
同时,大多数数字在相同的json中被缩放,四舍五入并很好地替换为-
{"dataMap":{"DATE":"19854","mean":"21778.4088","ByGroup":"Mean"},"rowNumber":66},{"dataMap":{"DATE":"19861","mean":"21547.0865","ByGroup":"Mean"},"rowNumber":67}
我无法弄清楚为什么某些特定数字存在问题。请帮助。