java - 如何在用指数显示之前确定 DecimalFormat 的最大大小?

标签 java android numbers decimal

我在 EditText 中显示的数字在太长之前可以达到 20 个字符 + 4 个小数点。我想要的数字比最后用 de exposant 显示的数字长,这样它就不会被截断。

例如:123456789 将按原样显示 123456789123456789123456 太长,将显示为 1.123456789E8(仅作为示例!)

我测试过这个:

DecimalFormat df = new DecimalFormat("#.####");
df.setMaximumIntegerDigits(20);

但是在 20char 之后,数字就不能正确显示了。例如:123456789123456789123456 变成了 56789123456789123456(中继 4 第一个数字。)

谢谢!

最佳答案

Decimal Formater java doc 描述了如何处理指数。

Scientific Notation

Numbers in scientific notation are expressed as the product of a mantissa and a power of ten, for example, 1234 can be expressed as 1.234 x 10^3. The mantissa is often in the range 1.0 <= x < 10.0, but it need not be. DecimalFormat can be instructed to format and parse scientific notation only via a pattern; there is currently no factory method that creates a scientific notation format. In a pattern, the exponent character immediately followed by one or more digit characters indicates scientific notation. Example: "0.###E0" formats the number 1234 as "1.234E3". ...

比较困难的部分是如何在普通记数法和科学记数法之间切换。 我通过在 Messageformater 中的一个 choide 格式器中嵌入两个十进制格式器来完成此操作:

MessageFormat format = new MessageFormat(
"{0,choice,0#{0,number,'#,##0.####'}|99999<{0,number,'000000.####E0'}}",
                Locale.ENGLISH);

(此示例只有 6 位小数,但您可以更改它。)

消息格式的用法与十进制格式器有点不同,因为格式方法需要一个对象数组。

System.out.println(format.format(new Object[] { 123 }));

它为 (1, 12, 123, ...) 打印的是:

1
1.1
12
123
1,234
12,345
123456E0
123456.7E1
123456.78E2
123456.789E3
123456.789E4
123456.789E5
123456.789E6

您需要稍微调整模式以使其符合您的 20 位要求,但方式应该很清楚。

即使我已经证明它有效,我还是建议实现您自己的 Formater,它使用 2 个十进制格式器和一个 if 条件。

关于java - 如何在用指数显示之前确定 DecimalFormat 的最大大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4808950/

相关文章:

android - 在广播接收器中发送位置

java - 将 float 格式化为 n 位小数

mysql - 我的十进制数在创建时会缩短,但在编辑时不会

java - Java中如何求两个给定整数之间的数字之和

java - 为什么我的简单应用程序没有收到 UDP 数据包

java - 配置 JanusGraph 以通过 Java 使用 ElasticSearch 和 Cassandra

android - 在没有应用程序崩溃的情况下无法使用 MapController

java - HSSFCell setCellStyle 在所有工作表的单元格而不是选定的单元格上应用样式

Java GregorianCalendar 和 DST 转换时间

android - 将应用栏 ScrollView 行为添加到 CoordinatorLayout 中的多个 View