JAVA How to remove trailing zeros from a double [d

2019-01-17 20:06发布

This question already has an answer here:

For example I need 5.0 to become 5, or 4.3000 to become 4.3.

3条回答
对你真心纯属浪费
2楼-- · 2019-01-17 20:28

You should use DecimalFormat("0.#")


For 4.3000

Double price = 4.3000;
DecimalFormat format = new DecimalFormat("0.#");
System.out.println(format.format(price));

output is:

4.3

In case of 5.000 we have

Double price = 5.000;
DecimalFormat format = new DecimalFormat("0.#");
System.out.println(format.format(price));

And the output is:

5
查看更多
Summer. ? 凉城
3楼-- · 2019-01-17 20:35

Use a DecimalFormat object with a format string of "0.#".

查看更多
甜甜的少女心
4楼-- · 2019-01-17 20:41

Use DecimalFormat

  double answer = 5.0;
   DecimalFormat df = new DecimalFormat("###.#");
  System.out.println(df.format(answer));
查看更多
登录 后发表回答