有没有更好的方法可以将Double转换为确切的十进制字符串? [英] Is there a better way to convert a Double to it's exact decimal String?

查看:285
本文介绍了有没有更好的方法可以将Double转换为确切的十进制字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了多种方法用String.format()和DecimalFormater将Double转换为它的精确十进制字符串,到目前为止,我发现了这一点:

I tried many ways to convert a Double to it's exact decimal String with String.format() and DecimalFormater and I found this so far :

String s = "-.0000000000000017763568394002505";
Double d = Double.parseDouble(s) * 100;
System.out.println((new java.text.DecimalFormat("###########################.################################################################################")).format(d));

https://ideone.com/WG6zeC

我并不是我的解决方案的忠实拥护者,因为做出巨大的预算对我来说是丑陋的

I'm not really a fan of my solution because it's ugly to me to make a huge pattern that does not covers all the cases.

您还有其他方法可以做到这一点吗?

我真的想拥有 ALL 小数,没有科学计数法没有尾随零位

Do you have another way to make this ?
I really want to have ALL the decimals, without scientific notation, without trailing zeros.

谢谢

PS:我需要在没有外部库且在Java 1.7中使用。

P.S.: I need this without external libraries and in Java 1.7.

推荐答案

似乎您必须处理一些精度。 double不适用于此用途。最好使用 BigDecimal

Seems as if you have to deal with some precision. double is not intended for this use. Better use BigDecimal

String value="13.23000";
BigDecimal bigD=new BigDecimal(value);
System.out.println(bigD);
System.out.println(bigD.stripTrailingZeros().toPlainString());

这篇关于有没有更好的方法可以将Double转换为确切的十进制字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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