微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java-如何确定DecimalFormat的最大大小,然后将其显示为指数?

我在EditText中显示一个数字,该数字可以太长,最多可以包含20个字符(四进制).我希望数字的长度大于结尾处显示的数字,因此不会被截断.

例如: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 diget要求相匹配,但是方法应该明确.

即使我证明它可以工作,我还是建议实现自己的格式化程序,该格式程序使用2个十进制格式化程序和一个if条件.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐