有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

用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) 个答案

  1. # 1 楼答案

    你可以这样做:

    //...
      float myFloatValue = BigDecimal.valueOf(23.0).floatValue();
      String formatted = String.format("%.4f", myFloatValue);
      System.out.println(formatted);
    //...