如何在不损失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(...)
。
- 无法从android studio中的另一个类访问变量的变量值
- 在Android中加密和解密zip文件?
- Espresso onData在视图上执行“加载适配器数据”时出错
- Android应用程序永远下载Web内容为字符串(WaitForGcToComplete阻止xx.xxxms导致HeapTrim?)
- 如何反序列化可能是字符串,对象或列表的json / gson
- 我是否需要在使用它的每个微服务(模块)中或仅在根应用程序中定义数据存储索引?
- 如何在Google App Engine Java应用程序之间共享模块之间的会话?
- 整数i = 3 vs Integer i = new Integer(3)
- 你用了什么Object.clone()?