Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/397.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Gson:将双精度值格式化为4位小数_Java_Json_Gson - Fatal编程技术网

Java Gson:将双精度值格式化为4位小数

Java Gson:将双精度值格式化为4位小数,java,json,gson,Java,Json,Gson,我怎样才能让Gson格式的双值四舍五入(或截断)到小数点后4位呢?我想出来了。可以使用类型适配器: GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(Double.class, (JsonSerializer<Double>) (src, typeOfSrc, context) -> { DecimalFormat df = new DecimalFormat("#.####");

我怎样才能让Gson格式的双值四舍五入(或截断)到小数点后4位呢?

我想出来了。可以使用类型适配器:

GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Double.class, (JsonSerializer<Double>) (src, typeOfSrc, context) -> {
    DecimalFormat df = new DecimalFormat("#.####");
    df.setRoundingMode(RoundingMode.CEILING);
    return new JsonPrimitive(Double.parseDouble(df.format(src)));
});
Gson gson = builder.create();
GsonBuilder=newgsonbuilder();
registerTypeAdapter(Double.class,(JsonSerializer)(src,typeOfSrc,context)->{
DecimalFormat df=新的DecimalFormat(“#.#####”);
df.设置圆形模式(圆形模式.天花板);
返回新的JsonPrimitive(Double.parseDouble(df.format(src));
});
Gson Gson=builder.create();

如果您在Kotlin中尝试此操作,Aman的答案仍然有效,但您必须使用类型标记,而不是Double.class(或Double::class.java):

builder.registerTypeAdapter(对象:TypeToken(){}.type。。。

以下snipet失败:
DecimalFormat df=new-DecimalFormat(“#.#.#.#.#.#.#.#.”);df.setRoundingMode(RoundingMode.天花板);Double.parseDouble(df.format(Double.valueOf(0.0123457d));
with
java.lang.NumberFormatException:用于输入字符串:“00124”.
因为您不在世界上的“十进制周期”区域,所以必须添加
df.setDecimalFormatSymbols(US\u FORMATTER\u SYMBOLS);
实际上,我认为这与
Math.rint(src*10000)的行为完全相同/10000
除非该值接近绝对最大双倍值。在这两种情况下,我认为如果你运气不好,它仍然可以使双倍带±1ulp的长尾。
builder.registerTypeAdapter(object: TypeToken<Double>() {}.type, ...