0

I'm writing a Java program to process electronic tax forms that come in some pseudo-xml format.
The resulting amount of tax to be paid or refunded comes in the following format: 13-char long String of unsigned integers where the last two represent the cents, i.e. two decimal places. Whether result is positive (payment) or negative (refund) is indicated elsewhere so it's not relevant here.

I need to convert this string to BigNumber and have come to the below solution, is a good way to go about it? Do you know any better solution?

public class BigDecimalTest {
    public static void main(String[] args) {

        // 0000000043272  for EUR 432.72
        String s = "0000000043272";    

        //mantissa is the amount as-is, exponent-2 since working with 2 decimal places.
        BigDecimal bd = new BigDecimal(s+"E-2"); 

        System.out.printf("%s: BigDecimal %sE-2 toString: %s\n", s, s, bd.toString());
    }
}
Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254
danirod
  • 1,011
  • 3
  • 9
  • 18
  • 6
    You could divide the number by 100; `BigDecimal bd = new BigDecimal(s).divide(new BigDecimal(100));`. If you do that, have 100 stored as a constant to avoid creating a new bigdecimal each time. – assylias May 16 '12 at 15:31
  • Or use BigDecimal.valueOf(100) and let it do the caching for you. – user207421 Sep 16 '12 at 21:28

2 Answers2

2

You could also use:

BigDecimal bd = new BigDecimal("1234").movePointLeft(2);

Creates a second instance, but is more readable.

Malcolm Smith
  • 3,540
  • 25
  • 29
  • 1
    Good one! Not sure if more efficient since it creates two BigDecimals but it's definitively more concise and clear. I believe my solution created only one instance but perhaps is a moot point. – danirod May 16 '12 at 15:52
  • @b4nd0ler0 More efficient than what? Dividing by 100 also creates two instances. – user207421 Sep 16 '12 at 21:29
  • the OP wasn't dividing by 100. He is appending an exponent modifier to the string, and initialising from that. Thinking about it, he does create an additional String instance in that process, so its no more efficient from an object creation perspective. – Malcolm Smith Sep 17 '12 at 20:55
1

Another alternative:

// making use of the constructor scale parameter
BigDecimal bd = new BigDecimal(new BigInteger(s), 2);  
GriffeyDog
  • 8,186
  • 3
  • 22
  • 34