我目前正在使用的方法是:
:
String.format("%.4", myDouble);
问题在于,如果我得到一个小数点后面位数较少的数字,比如2.34,它将显示为2.3400。有没有办法避免这种情况?
DecimalFormat
和模式#.####
应该可以。它将显示小数点后的最多4位数字,但如果没有必要,则可能会少。Math.round(192.15515452*10000)/10000.0
返回 192.1551
而 Math.round(192.15*10000)/10000.0
返回 192.15
DecimalFormat
和一个模式。double value = 2.34;
String pattern = "#.####";
DecimalFormat myFormatter = new DecimalFormat(pattern);
String output = myFormatter.format(value);
System.out.println(value + " " + pattern + " " + output); // displays 2.34 #.#### 2.34
DecimalFormat
格式化十进制数... - Codebender