Java 对象格式为带小数的字符串数字

Java Object format to String Number with Decimals

所以我有一个对象数组列表,其中有字符串编号。我想为这些数字 (8) 添加小数位。

String value = String.valueOf(accountEntry.get(4));
double amount = Double.valueOf(value);

String formatted = String.format(Locale.GERMANY,"%.8f",amount);
accountEntry.add(formatted);

例如 101700000000 应该输出 1017 而不是 101700000000,00000000 有谁知道问题出在哪里?

Does anyone know where the problem is?

您的输入是:101700000000 并且您正在格式化 String.format(Locale.GERMANY,"%.8f",amount); 在这里您的输出将是 101700000000,00000000 因此要了解此字符串格式不会将您的输入神奇地转换为 1017。您需要使用另一个这个问题的算法

您好,使用 Regex 试试这样的操作,这样您就可以删除末尾的所有零。

String value = String.valueOf("101700000000");
double amount = Double.valueOf(value);
String formatted = String.format(Locale.GERMANY,"%d",(long)amount);
formatted = formatted.replaceAll("0+$", "");
System.out.println(formatted);

输入:101700000000 ===> 输出:1017