如何将BigInteger转换为科学记数法字符串并返回?
我想将BigInteger数转换为像1.86e + 6这样的小型科学符号,并再次将该科学符号转换为Java中的BigInteger数。 请帮忙。
最简单的方法是使用BigDecimal
来解析或输出科学记数法字符串。
你可以这样做:
BigDecimal bd = new BigDecimal("1.86E+6"); BigInteger bi = bd.toBigInteger();
并反转:
bd = new BigDecimal(bi); String s = bd.toString();
更新
如果需要更多用户定义的输出,则可以使用NumberFormatter
。 不要忘记将Locale
为类似Locale.ROOT
东西,所以你不会得到,比如逗号作为小数分隔符(这是我在德语区域设置中首先得到的)。 例:
// Create a large, ugly number. BigInteger bi = BigInteger.valueOf(1001).pow(345); // Convert to scientific notation using invariant Locale.ROOT NumberFormat formatter = new DecimalFormat("0.######E0", DecimalFormatSymbols.getInstance(Locale.ROOT)); String str = formatter.format(bi); System.out.println(bi); System.out.println(); System.out.println(str); // No need for a formatter here. BigDecimal bd = new BigDecimal(str); BigInteger output = bd.toBigInteger(); System.out.println(); System.out.println(output);
这个输出是:
1.411747E1035
(是的,BigIntegers可能很笨重)。
我不知道你的价值有多大,但上面的效果在我的Mac上运行良好。 当然,使用只有几位小数的科学记数法会失去很多精确度。