有没有办法在 JSONArray 中舍入双精度数?

问题描述 投票:0回答:1

我有 JSON 文本格式。因此,我首先将其放入对象,然后放入 Map,其中值中有另一个映射(JSON 在文本格式中具有内部和外部映射类型)。在内部地图中打印带有两位小数的 JSONDouble 不是问题(我可以只使用

printf("%.2f"))
但当 JSONArray 出现时我不能这样做。

我尝试过

printf
功能,但不起作用。

如果可以不使用流那就完美了。

这是代码:

try {
    response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
} catch (IOException e) {
    e.printStackTrace();
} catch (InterruptedException e) {
    e.printStackTrace();
}

System.out.println(response.body());
System.out.println();

Object obj = new JSONParser().parse(response.body());

Map<String, Map<String, Float>> output = (Map) obj;

System.out.printf("%.2f%n", output.get("outputs").get("ac_annual"));
System.out.printf("%.2f%n", output.get("outputs").get("solrad_annual"));
System.out.printf("%.2f%n", output.get("outputs").get("capacity_factor"));
System.out.println(output.get("outputs").get("ac_monthly"));
System.out.println(output.get("outputs").get("dc_monthly"));
System.out.println(output.get("outputs").get("poa_monthly"));
System.out.println(output.get("outputs").get("solrad_monthly"));

和输出:

4130,28
3,60
11,79
[350.4450331552693,436.3879540968705,340.7495159069064,442.1920779147474,534.4142671193669,19.89441005557222,206.6577352851099,492.4427511771748,241.7735300594523,382.6085934358003,376.0863140563925,306.6293313390505]
[368.0682926594546,457.2045927636358,359.1841462238203,464.7078109487218,561.0990701509306,27.17952816676697,221.2817047541209,517.4117655437504,256.4903025712858,402.0961281476057,394.804951938705,322.3432439889111]
[104.9805590746965,131.3527386112043,104.2011355720695,138.6804496432297,177.348356252559,9.001239090243104,70.67352420990476,166.9411671806375,79.89308311196012,122.4161912004151,115.6650356864296,91.94797329425062]
[3.386469647570856,4.69116923611444,3.361326953937725,4.622681654774324,5.720914717824484,0.3000413030081034,2.279791103545315,5.385198941310887,2.663102770398671,3.948909393561777,3.855501189547655,2.966063654653246]
java arrays json dictionary rounding
1个回答
0
投票

所以你做对了。您所需要做的就是从

JSONArray
获取所有值,分别转换它们并构建
String
数组。

public static String toString(JSONArray jsonArray) {
    return IntStream.rangeClosed(0, jsonArray.length())
            .mapToObj(i -> String.format("%.2f", (BigDecimal) jsonArray.get(i)))
            .collect(Collectors.joining(",", "[", "]"));
}
© www.soinside.com 2019 - 2024. All rights reserved.