如何在不损失Java精度的情况下将String转换为Double? [英] How can I convert String to Double without losing precision in Java?

查看:1652
本文介绍了如何在不损失Java精度的情况下将String转换为Double?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试如下

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

输出:
12.0

Output: 12.0

但我希望得到12.00精度

But i want to get 12.00 precision

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

please let me know correct way without using format() method in string class

推荐答案

使用 BigDecimal 而不是双倍:

Use BigDecimal Instead of a 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(十进制); 将其转储出来,则会打印出 12.00

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.

这篇关于如何在不损失Java精度的情况下将String转换为Double?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆