case 1:

String str=new BigDecimal(123.9).toString()

输出str:123.900000000000005684341886080801486968994140625

解决方案:

String str=BigDecimal.valueOf(123.9).toString()

 

 

case2:

//数据库中该字段类型为decimal(20, 2),值为200.10
BigDecimal num = testMapper.query();
//值为200.1
String str = testDTO.getNum();
//比较BigDecimal与String:
if (num != null) {
    boolean ifEquals = num.toString.equals(str);
}            

结果为:false

解决方案:比较两个BigDecimal要通过BigDecimal的compareTo()方法。

 

 

case3:

不要直接比较double、float类型的值,因为他们可能是不准确的。建议转成BigDecimal进行比较,String也不建议,因为如3.14 != 3.140。另外,数字后f、d表示float与double,也就意味着他们的精度是不同的:

    public static void main(String[] args) {
        double a = 3.14f;
        double b = 3.14;
        System.out.println(a == 3.14);
        System.out.println(b == 3.14);
        System.out.println(a);
        System.out.println(b);
    }

关于BigDecimal转String的准确性问题

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-12-13
  • 2021-09-24
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-06-02
  • 2021-12-06
  • 2021-12-06
  • 2021-09-24
  • 2022-12-23
相关资源
相似解决方案