我们有一个 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
你可以这样做:
//...
float myFloatValue = BigDecimal.valueOf(23.0).floatValue();
String formatted = String.format("%.4f", myFloatValue);
System.out.println(formatted);
//...
String 如何格式化 0.4f amount 变量?这不是最终值,但是!