保留两位有效数字可以使用DecimalFormat来实现;

        String str = "195.1";
        BigDecimal bigDecimal = new BigDecimal(str);
        BigDecimal bigDecimal1 = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
        System.out.println(bigDecimal1.toString());

        // 如果位数不足不会以0填充
        DecimalFormat format = new DecimalFormat("#.##");
        String format1 = format.format(Double.parseDouble(str));
        System.out.println(format1);

        // 如果位数不足则以0填充
        DecimalFormat format2 = new DecimalFormat("#.00");
        String format3 = format2.format(Double.parseDouble(str));
        System.out.println(format3);

 

相关文章:

  • 2021-07-16
  • 2021-11-22
  • 2022-12-23
  • 2021-12-10
  • 2022-12-23
  • 2022-12-23
  • 2022-01-07
  • 2021-09-07
猜你喜欢
  • 2022-12-23
  • 2021-10-22
  • 2021-07-13
  • 2022-12-23
  • 2021-06-18
  • 2022-12-23
  • 2021-12-25
相关资源
相似解决方案