Convert Java Number to BigDecimal : best way

前端 未结 3 1056
离开以前
离开以前 2020-12-29 01:11

I am looking for the best way to convert a Number to a BigDecimal.

Is this good enough?

Number number;
BigDecimal big = new BigDecimal(number.toStrin         


        
相关标签:
3条回答
  • 2020-12-29 01:27

    The best way is

    BigDecimal.valueOf(myDouble);
    

    It's the same internally, but it's an overloaded function that works also for longs and it's optimized for frequently used longs value. So it's more standard, simple and easy to remember.

    Source

    0 讨论(0)
  • 2020-12-29 01:38

    This is fine, remember that using the constructor of BigDecimal to declare a value can be dangerous when it's not of type String. Consider the below...

    BigDecimal valDouble = new BigDecimal(0.35);
    System.out.println(valDouble);
    

    This will not print 0.35, it will infact be...

    0.34999999999999997779553950749686919152736663818359375
    

    I'd say your solution is probably the safest because of that.

    0 讨论(0)
  • 2020-12-29 01:42

    Can we lose precision with toString() method ?

    Kind of ... Both Float.toString() and Double.toString() only output the number of digits after the decimal separator, which is required for the output uniquely to correspond to a float or double value.

    To use the 0.35 example in david99world's answer, consider the following code:

    BigDecimal bd1 = new BigDecimal(0.35);
    
    Number n = 0.35;
    BigDecimal bd2 = new BigDecimal(n.toString());
    
    System.out.println(bd1);
    System.out.println(bd2);
    

    An intuitive expectation may be that the two BigDecimal instances are identical, but the output shows that they are not:

    0.34999999999999997779553950749686919152736663818359375
    0.35
    

    The first line is the exact value of the double, since 0.35 cannot be represented exactly. The second line is 0.35, since no more fractional digits are required to represent the distinct value. E.g. the statement 0.34999999999999997779553950749686919152736663818359375 == 0.35 will evaluate to true.

    This is actually not a loss of precision when creating the BigDecimal, the uncertainty is already there in your "source" value. The problem is rather that the discrete values possible using e.g. a float or double value as source not necessarily will be represented by the exact equivalent in the BigDecimal instance.

    0 讨论(0)
提交回复
热议问题