如果不是零,则格式化float以显示小数位

Rod*_*cha 4 java regex floating-point decimalformat

我需要仅在与零不同时显示浮点值的小数位.

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

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

din*_*o10 10

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

// 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
Run Code Online (Sandbox Code Playgroud)