简体   繁体   English

如何在不使用尾数/指数格式的情况下打印浮点值?

[英]How can floating point values be printed without mantissa/exponent format?

I am trying to print a double value. 我正在尝试打印一个双精度值。 It is printing in matissa and exponent format, which is not what I want. 它以matissa和指数格式打印,这不是我想要的。 For example, my program prints 1.234567E6 for the value 1243567. How can I make it print 1234657 ? 例如,我的程序将打印1.234567E6的价值1243567.我怎样才能使它打印1234657

BigDecimal.valueOf(double).toPlainString();

您可能会研究NumberFormat类和DecimalFormat

I have been struggling with exactly the same problem, and the two answers here provide a clue on how to solve the problem: use a formatter. 我一直在为完全相同的问题而苦苦挣扎,这里的两个答案提供了有关如何解决问题的线索:使用格式化程序。 Neither answer explains precisely what parameters are needed to format a Double value, and avoid exponential notation. 这两个答案都无法准确地说明格式化Double值和避免使用指数表示法所需的参数。

There are two options. 有两种选择。 These are described in the documentation as "d" for decimal integer and "f" for decimal number. 这些在文档中被描述为“ d”代表十进制整数,“ f”代表十进制数。 What I actually need is "fixed point" format, and that is not clearly described by the documentation, however f will give you fixed point if you set the parameters correctly. 我真正需要的是“定点”格式,文档中对此没有明确说明,但是如果正确设置参数,f会为您提供定点。 It will also give you an integer display if you set decimal points to zero. 如果将小数点设置为零,它还将为您提供整数显示。

For a Double value 12345678 formatting gives you the following results: 对于Double值12345678,格式化将为您提供以下结果:

Double d = Double.parseDouble("12345678");
String r1 = String.format("%f",d);        // 12345678.000000
String r2 = String.format("%10f",d);      // 12345678.000000
String r3 = String.format("%5.2f",d);     // 12345678.00
String r4 = String.format("%5.0f",d);     // 12345678
String r5 = String.format("%,f",d);       // 12,345,678.000000
String r6 = String.format("%,5.0f",d);    // 12,345,678
String r7 = String.format("%d",d);        // throws an exception!

On the last one, even though you want an integer display of the number, you can not use the 'd' option with a Double. 在最后一个上,即使您希望整数显示数字,也不能将'd'选项与Double一起使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM