Format float to show decimal places if is not zero java [duplicate]

ⅰ亾dé卋堺 提交于 2019-12-06 04:06:16

问题


I need to to show decimal places of a float value only when it is different from zeros.

  1. 5.0 should be shown as 5.
  2. 7.3 should be shown as 7.3.
  3. 9.000003 should be shown as 9.000003.

How to format in this way using regex or DecimalFormat?


回答1:


To display decimals the way you desire, use the following snippet:

// 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


来源:https://stackoverflow.com/questions/38424291/format-float-to-show-decimal-places-if-is-not-zero-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!