Java:使用DecimalFormat格式化双精度和整数,但保留不带小数分隔符的整数

前端之家收集整理的这篇文章主要介绍了Java:使用DecimalFormat格式化双精度和整数,但保留不带小数分隔符的整数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图在 Java程序中格式化一些数字.数字将是双精度和整数.处理双精度时,我只想保留两个小数点,但是当处理整数时,我希望程序保持不变.换一种说法:

双打 – 输入

  1. 14.0184849945

双打 – 输出

  1. 14.01

整数 – 输入

  1. 13

整数 – 输出

  1. 13 (not 13.00)

有没有办法在相同的DecimalFormat实例中实现?我的代码如下,到目前为止:

  1. DecimalFormat df = new DecimalFormat("#,###,##0.00");
  2. DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.ENGLISH);
  3. otherSymbols.setDecimalSeparator('.');
  4. otherSymbols.setGroupingSeparator(',');
  5. df.setDecimalFormatSymbols(otherSymbols);

解决方法

您可以将minimumFractionDigits设置为0.像这样:
  1. public class Test {
  2.  
  3. public static void main(String[] args) {
  4. System.out.println(format(14.0184849945)); // prints '14.01'
  5. System.out.println(format(13)); // prints '13'
  6. System.out.println(format(3.5)); // prints '3.5'
  7. System.out.println(format(3.138136)); // prints '3.13'
  8. }
  9.  
  10. public static String format(Number n) {
  11. NumberFormat format = DecimalFormat.getInstance();
  12. format.setRoundingMode(RoundingMode.FLOOR);
  13. format.setMinimumFractionDigits(0);
  14. format.setMaximumFractionDigits(2);
  15. return format.format(n);
  16. }
  17.  
  18. }

猜你在找的Java相关文章