如果不为零,则格式化浮点数以显示小数位 java

Format float to show decimal places if is not zero java

仅当浮点值不为零时,我才需要显示其小数位。

  1. 5.0 应显示为 5.
  2. 7.3 应显示为 7.3.
  3. 9.000003 应显示为 9.000003.

如何使用正则表达式或 DecimalFormat 以这种方式格式化?

要以您希望的方式显示小数,请使用以下代码段:

// This is to show symbol . instead of ,
DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.US);
// Define the maximum number of decimals (number of symbols #)
DecimalFormat df = new DecimalFormat("#.##########", otherSymbols);

// type: double
System.out.println(df.format(5.0)); // writes 5
System.out.println(df.format(7.3)); // writes 7.3
System.out.println(df.format(9.000003)); // writes 9.000003

// type: float
System.out.println(df.format(9.000003f)); // writes 9.000002861