如何在不损失Java精度的情况下将String转换为Double?

试过如下

String d=new String("12.00"); Double dble =new Double(d.valueOf(d)); System.out.println(dble); 

输出:12.0

但我希望得到12.00精度

请不要在字符串类中使用format()方法让我知道正确的方法

使用BigDecimal而不是double:

 String d = "12.00"; // No need for `new String("12.00")` here BigDecimal decimal = new BigDecimal(d); 

这是有效的,因为BigDecimal维护一个“精度”, BigDecimal(String)构造函数设置从数字右边的位数. ,并在toString使用它。 所以,如果你只是用System.out.println(decimal);将其转储出去System.out.println(decimal); ,打印出12.00

您的问题不是精度损失,而是数字的输出格式及其小数位数。 您可以使用DecimalFormat来解决您的问题。

 DecimalFormat formatter = new DecimalFormat("#0.00"); String d = new String("12.00"); Double dble = new Double(d.valueOf(d)); System.out.println(formatter.format(dble)); 

我还要补充一点,你可以使用DecimalFormatSymbols来选择使用哪个小数分隔符。 例如,一点:

 DecimalFormatSymbols separator = new DecimalFormatSymbols(); separator.setDecimalSeparator('.'); 

然后,在声明DecimalFormat同时:

 DecimalFormat formatter = new DecimalFormat("#0.00", separator); 

你没有失去任何精度,12.0正好等于12.00。 如果要显示或打印2位小数,请使用java.text.DecimalFormat

如果要格式化输出,请使用PrintStream #format(…) :

 System.out.format("%.2f%n", dble); 

%.2f – 小数点后的两个位置和%n – 换行符。

更新:

如果您不想使用PrintStream#format(...) ,请使用DecimalFormat#format(...)