gladis
gladis

Reputation: 103

String to BigDecimal, which one is good approch

I am trying to convert string to BigDecimal. Please tell which one is below is good approch

BigDecimal selAmount = BigDecimal.ZERO;
String amount = "1234";
selAmount = BigDecimal.valueOf(Double.parseDouble(amount));

or

selAmount = new BigDecimal(amount);

Upvotes: 2

Views: 112

Answers (5)

Andy Turner
Andy Turner

Reputation: 140504

Don't use the first approach. If the string represents a value which can't be exactly represented by a double, you'll get accuracy issues.

You can't use the second approach either, since there is no overload of BigDecimal.valueOf which accepts a String.

So, option 3:

BigDecimal selAmount = new BigDecimal(amount);

Upvotes: 1

Dark Army
Dark Army

Reputation: 268

Passing string as a constructor is better way. You will lose precision in the first case.

e.g

String s = "123";
BigDecimal bigDecimal = new BigDecimal(s);

Upvotes: 0

TheLostMind
TheLostMind

Reputation: 36304

BigDecimal.valueOf(double)); calls return new BigDecimal(Double.toString(val)); implicitly. So, your second case would be more efficient, and as Thilo says, more correct.

Code :

 */
public static BigDecimal valueOf(double val) {
    // Reminder: a zero double returns '0.0', so we cannot fastpath
    // to use the constant ZERO.  This might be important enough to
    // justify a factory approach, a cache, or a few private
    // constants, later.
    return new BigDecimal(Double.toString(val));
}

Upvotes: 0

Rahul Tripathi
Rahul Tripathi

Reputation: 172578

The second approach is better to proceed with, simply pass the string to the constructor of BigDecimal. The first approach may have precision issues.

From JavaDocs has

public BigDecimal(String val)

Translates the string representation of a BigDecimal into a BigDecimal. The string representation consists of an optional sign, '+' ( '\u002B') or '-' ('\u002D'), followed by a sequence of zero or more decimal digits ("the integer"), optionally followed by a fraction, optionally followed by an exponent.

Upvotes: 0

RockAndRoll
RockAndRoll

Reputation: 2287

You can pass string directly to the constructor of BigDecimal.

Upvotes: 0

Related Questions