用java从JSON响应读取十进制值
我们有一个API,它返回以下响应:
{
"Amount": 10.2300,
"name": "Test"
}
Amount
在小数点后有4位。我们需要验证小数位应该是4位,
代码如下:
String strres = response.asString();
System.out.println("strres" + strres);
JSONObject data = new JSONObject(strres);
float myFloatValue = BigDecimal.valueOf(data.getDouble("Amount")).floatValue();
System.out.println("The Amount " + myFloatValue);
执行后,我们得到:myFloatValue = 10.23
,而不是10.2300
,因此小数位数小于4。
请建议我们如何阅读而不丢失小数点
sAmount = response.jsonPath().get("Amount").toString()
String[] splitter = sAmount.toString().split("\\.");
splitter[0].length();
splitter[1].length();
当存储到String
变量时,也会得到相同的值:10.23
# 1 楼答案
你可以这样做: