JAVA如何从double中删除尾随零

例如,我需要5.0变为5 ,或4.3000变为4.3

使用DecimalFormat

  double answer = 5.0; DecimalFormat df = new DecimalFormat("###.#"); System.out.println(df.format(answer)); 

你应该使用DecimalFormat("0.#")


对于4.3000

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

输出是:

 4.3 

如果是5000,我们有

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

输出是:

 5 

使用格式字符串为“0。#”的DecimalFormat对象。