简体   繁体   English

在Java中打印double,不包括无效的零

[英]Print double in Java excluding insignificant zeros

I need to print doubles rounded to a variable number of digits after decimal point so that insignificant zeros are not printed. 我需要在小数点后打印四舍五入到可变位数的双精度数,这样就不会打印出无效的零。 Eg I want both numbers 123 and 123.4 to be printed as is -- the first one without decimal point and the second one with it. 例如,我希望数字123和123.4都按原样打印 - 第一个没有小数点,第二个没有小数点。 If there are more than significant digits after decimal point then the number should be truncated to six digits. 如果小数点后有多位有效数字,则该数字应截断为六位数。

What I describe is the default behavior of boost::locale::format if you print numbers as boost::locale::format("{1,number}") % double_value . 如果您将数字打印为boost::locale::format("{1,number}") % double_value我所描述的是boost :: locale :: format的默认行为。 What I need is to do the same in Java, desirably using String.format. 我需要的是在Java中做同样的事情,最好使用String.format。 I tried %f and %g , but both of them print at least six digits. 我尝试了%f%g ,但它们都打印了至少六位数。

All numbers I want to format are in range [0.1, 30000] so turning to scientific form should not be a pain here. 我想要格式化的所有数字都在[0.1,30000]范围内,所以转向科学形式不应该是一种痛苦。

Use DecimalFormat as explained here . 使用的DecimalFormat作为解释在这里

DecimalFormat df = new DecimalFormat("#0.######");
df.format(0.912385);

There are various methods to format floating point numbers in Java. 在Java中格式化浮点数有多种方法。

First, format string allow you to specify a precision . 首先,格式字符串允许您指定精度 The following code 以下代码

System.out.printf("%.2f - %.2f", 123, 123.4) 

will display 123.00 - 123.40 . 将显示123.00 - 123.40 Note that this is not exactly what you asked for, because the displayed numbers always have two fractional digits. 请注意,这并不是您要求的,因为显示的数字始终有两个小数位。

For more control over the format of the numbers, you can use the DecimalFormat class. 要更好地控制数字的格式,可以使用DecimalFormat类。 The following code has the behaviour you describe: 以下代码具有您描述的行为:

DecimalFormat form = new DecimalFormat("#.##");
form.setRoundingMode(RoundingMode.HALF_UP);
System.out.printf("%s - %s", form.format(123), form.format(123.4));

outputs: 123 - 123.4 . 输出: 123 - 123.4

使用:

String.format("%.2f", floatValue);

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

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