【问题标题】:Format float to show decimal places if is not zero java [duplicate]如果不为零,则格式化浮点以显示小数位java [重复]
【发布时间】:2016-07-17 17:59:25
【问题描述】:

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

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

如何使用 regex 或 DecimalFormat 以这种方式格式化?

【问题讨论】:

标签: java regex floating-point decimalformat


【解决方案1】:

要以您想要的方式显示小数,请使用以下 sn-p:

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

【讨论】:

    猜你喜欢
    • 2016-10-04
    • 2016-02-09
    • 2018-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多