Java BigDecimal without E

前端 未结 4 2097
抹茶落季
抹茶落季 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 13:44

    Perhaps using BigDecimal isn't really helping you.

    double d = 5521.0000000001;
    double f = d - (long) d;
    System.out.printf("%.10f%n", f);
    

    prints

    0.0000000001
    

    but the value 5521.0000000001 is only an approximate representation.

    The actual representation is

    double d = 5521.0000000001;
    System.out.println(new BigDecimal(d));
    BigDecimal db = new BigDecimal(d).subtract(new BigDecimal((long) d));
    System.out.println(db);
    

    prints

    5521.000000000100044417195022106170654296875
    1.00044417195022106170654296875E-10
    

    I suspect whatever you are trying to is not meaningful as you appear to be trying to obtain a value which is not what you think it is.

    0 讨论(0)
  • 2021-01-11 13:46

    To get a String representation of the BigDecimal without the exponent part, you can use
    BigDecimal.toPlainString(). In your example:

    BigDecimal x = new BigDecimal("5521.0000000001");
    x = x.add(new BigDecimal("-1").
                  multiply(x.divideToIntegralValue(new BigDecimal("1.0"))));
    System.out.println(x.toPlainString());
    

    prints

    0.0000000001
    
    0 讨论(0)
  • 2021-01-11 14:04

    Try using BigDecimal.toPlainString() to get value as plain string as you require.

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题