java - 如何在不丢失Java精度的情况下将String转换为Double?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15298232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I convert String to Double without losing precision in Java?
提问by user1938073
Tried as below
试过如下
String d=new String("12.00");
Double dble =new Double(d.valueOf(d));
System.out.println(dble);
Output: 12.0
输出:12.0
But i want to get 12.00 precision
但我想获得 12.00 的精度
please let me know correct way without using format() method in string class
请让我知道在字符串类中不使用 format() 方法的正确方法
回答by Rob
Your problem is not a loss of precision, but the output format of your number and its number of decimals. You can use DecimalFormat
to solve your problem.
您的问题不是精度损失,而是数字的输出格式及其小数位数。您可以使用它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));
I will also add that you can use DecimalFormatSymbols
to choose which decimal separator to use. For example, a point :
我还要补充一点,您可以使用它DecimalFormatSymbols
来选择要使用的小数点分隔符。例如,一个点:
DecimalFormatSymbols separator = new DecimalFormatSymbols();
separator.setDecimalSeparator('.');
Then, while declaring your DecimalFormat
:
然后,同时声明您的DecimalFormat
:
DecimalFormat formatter = new DecimalFormat("#0.00", separator);
回答by PermGenError
Use BigDecimal
Instead of a double:
使用BigDecimal
而不是双:
String d = "12.00"; // No need for `new String("12.00")` here
BigDecimal decimal = new BigDecimal(d);
This works because BigDecimal
maintains a "precision," and the BigDecimal(String)
constructor sets that from the number of digits to the right of the .
, and uses it in toString
. So if you just dump it out with System.out.println(decimal);
, it prints out 12.00
.
这是有效的,因为BigDecimal
维护了一个“精度”,并且BigDecimal(String)
构造函数将它从 的位数设置为.
,并在 中使用它toString
。所以如果你只是把它转储出来System.out.println(decimal);
,它会打印出来12.00
。
回答by jalynn2
You have not lost any precision, 12.0 is exactly equal to 12.00. If you want to display or print it with 2 decimal places, use java.text.DecimalFormat
您没有丢失任何精度,12.0 正好等于 12.00。如果要显示或打印 2 位小数,请使用java.text.DecimalFormat
回答by bsiamionau
If you want to format output, use PrintStream#format(...):
如果要格式化输出,请使用PrintStream#format(...):
System.out.format("%.2f%n", dble);
There %.2f
- two places after decimal point and %n
- newline character.
有%.2f
- 小数点后两位和%n
- 换行符。
UPDATE:
更新:
If you don't want to use PrintStream#format(...)
, use DecimalFormat#format(...)
.
如果您不想使用PrintStream#format(...)
,请使用DecimalFormat#format(...)
。