将 BigDecimal 转换为双精度值

我想问一下如何用指数将我所有的字符串转换为双倍。当我使用长度超过 7 的字符串时,它运行良好。

new BigDecimal("12345678").doubleValue() => 1.2345678E7

但七及以下我不能导出指数数。

new BigDecimal("1234567").doubleValue() => 1234567.0

我想要的是 1.234567E6。

有没有办法做到这一点?我已经搜索了一段时间,但一无所获。

问题是我返回的类型必须是 double 。将值转换为七以下后,我只能得到没有指数的值。

double test = new BigDecimal("1.234567E6").doubleValue() ;//output 1234567.0

但我需要它是 1.234567E6 并返回给调用者。那不可能吗?


慕桂英546537
浏览 218回答 3
3回答

繁星淼淼

您应该知道1.2345678e7和12345678.0是完全相同的值,只是具有不同的文本表示。你也可以代表1234567.0为1.234567e6。也是完全相同的 double,只是写出来的方式不同。默认输出以指数格式(“e-form”)显示超过一定数量有效数字的值,否则为纯十进制格式。因此,您可能想要更改收到的双打格式。这可以通过例如DecimalFormat或String.format()或类似来完成。这不会改变双打,只会改变它们在字符串中的呈现方式。

肥皂起泡泡

对于您的问题,您想将值转换为BigDecimal指数,您可以使用DecimalFormat. 您还可以更改输出值数字的比例。import java.math.*;import java.text.*;public class HelloWorld{&nbsp; &nbsp; &nbsp;public static void main(String []args){&nbsp; &nbsp; &nbsp; &nbsp; double a = new BigDecimal("1234567").doubleValue();&nbsp; &nbsp; &nbsp; &nbsp; String b;&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(a);&nbsp; &nbsp; &nbsp; &nbsp; NumberFormat formatter = new DecimalFormat("0.0E0");&nbsp; &nbsp; &nbsp; &nbsp; formatter.setRoundingMode(RoundingMode.DOWN);&nbsp; &nbsp; &nbsp; &nbsp; formatter.setMinimumFractionDigits(5); //<---Scale&nbsp; &nbsp; &nbsp; &nbsp; b = formatter.format(a);&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(b);&nbsp; &nbsp; &nbsp;}}输出将类似于:1234567.0 //Unformatted Value1.23456E6 //Formatted Value

狐的传说

见关于剖面科学记数法中java.text.DecimalFormat中。例如,&nbsp; &nbsp; DecimalFormat scientificFormat = new DecimalFormat("0.###E0");&nbsp; &nbsp; System.out.println(scientificFormat.format(BigDecimal.valueOf(123456L)));&nbsp; &nbsp; System.out.println(scientificFormat.format(BigDecimal.valueOf(1234567L)));&nbsp; &nbsp; scientificFormat.setMinimumFractionDigits(10);&nbsp; &nbsp; System.out.println(scientificFormat.format(BigDecimal.valueOf(12345678L)));会给你1,235E51,235E61,2345678000E7更改模式以匹配您要查找的内容。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java