Java BigDecimal without E

前端 未结 4 2101
抹茶落季
抹茶落季 2021-01-11 13:38

I have a BigDecimal variable

BigDecimal x = new BigDecimal(\"5521.0000000001\");

Formula:

x = x.add(new BigDecimal(\"-1\")
         


        
4条回答
  •  执念已碎
    2021-01-11 14:04

    If you want to do this at your BigDecimal object and not convert it into a String with a formatter you can do it on Java 8 with 2 steps:

    1. stripTrailingZeros()
    2. if scale < 0 setScale to 0 if don't like esponential/scientific notation

    You can try this snippet to better understand the behaviour

    BigDecimal bigDecimal = BigDecimal.valueOf(Double.parseDouble("50"));
    bigDecimal = bigDecimal.setScale(2);
    bigDecimal = bigDecimal.stripTrailingZeros();
    if (bigDecimal.scale()<0)
    bigDecimal= bigDecimal.setScale(0);
    System.out.println(bigDecimal);//50
    bigDecimal = BigDecimal.valueOf(Double.parseDouble("50.20"));
    bigDecimal = bigDecimal.setScale(2);
    bigDecimal = bigDecimal.stripTrailingZeros();
    if (bigDecimal.scale()<0)
    bigDecimal= bigDecimal.setScale(0);
    System.out.println(bigDecimal);//50.2
    bigDecimal = BigDecimal.valueOf(Double.parseDouble("50"));
    bigDecimal = bigDecimal.setScale(2);
    bigDecimal = bigDecimal.stripTrailingZeros();
    System.out.println(bigDecimal);//5E+1
    bigDecimal = BigDecimal.valueOf(Double.parseDouble("50.20"));
    bigDecimal = bigDecimal.setScale(2);
    bigDecimal = bigDecimal.stripTrailingZeros();
    System.out.println(bigDecimal);//50.2
    

提交回复
热议问题