简体   繁体   English

如何使用DecimalFormat仅在“带小数”的数字中隐藏尾随零

[英]How to use DecimalFormat to hide trailing zero in numbers “with decimals” only

I'm using DecimalFormat to remove trailing zeros from my outputs using the pattern #.# this produces outputs like 我正在使用DecimalFormat使用模式#.#从我的输出中删除尾随零,这会产生类似

12.5 --> 12.5 12.5-> 12.5

12 --> 12 12-> 12

however I need to make it produce 但是我需要使它产生

12.5 --> 12.5 12.5-> 12.5

12 --> 12.0 12-> 12.0

How can this happen ? 怎么会这样呢?

The Javadoc for DecimalFormat says that the 0 symbol represents a digit, while # will remove the zero if it is leading or trailing. Javadoc for DecimalFormat表示0符号代表一个数字,而#将在开头或结尾处删除零。 For example: 例如:

import java.text.DecimalFormat;

public class Main
{
  public static void main(String[] args)
  {
    DecimalFormat zeroes = new DecimalFormat("0.0");
    DecimalFormat hashes = new DecimalFormat("#.#");

    System.out.println(zeroes.format(12.0)); // 12.0
    System.out.println(zeroes.format(12.5)); // 12.5
    System.out.println(hashes.format(12.0)); // 12
    System.out.println(hashes.format(12.5)); // 12.5
  }
}

You have to use #.0 to show the digit. 您必须使用#.0来显示数字。 # treat 0 as absent. #将0视为不存在。

https://developer.android.com/reference/java/text/DecimalFormat.html https://developer.android.com/reference/java/text/DecimalFormat.html

You can also set max and min precision by: 您还可以通过以下方式设置最大和最小精度:

decimalFormat.setMaximumFractionDigits(maxPrecision);
decimalFormat.setMinimumFractionDigits(minPrecision);

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

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