javaformattingnumber-formattingcobol

# Convert a decimal number in Java into its assumed decimal Cobol representation

I have a requirement to convert a regular number (most likely with 2 decimal digits) into its respective Cobol counterpart with so called assumed decimal point in the following format: `9(9)v99`.

I already have a way to right align and pad it with zeroes, which is part of the requirement, just need to come up with a generic way to convert something like `1234.56` into its Cobol equivalent: `123456`.

Is there any good way to do it in Java 8, or perhaps a framework that does Cobol formatting conversions like that?

Solution

• I've experimented a little bit more with the existing Java facilities, and stumbled upon the `movePointRight(int n)` on `BigDecimal` type which seems to be doing what @rzwitserloot suggests but more declaratively.

Put together the below randomized test and ran it enough times (it seems) to eliminate any edge cases, as the result comes out green:

``````for (int i = 0; i < 100000; i++) {
Faker faker = new Faker();
String number = faker.expression("#{numerify '######.##'}");
System.out.println("string: " + number);
BigDecimal bdNumber = new BigDecimal(number);

bdNumber.movePointRight(2);
BigDecimal bdNumberMovedRight = bdNumber.movePointRight(2);
System.out.println("bdNumberMovedRight: " + bdNumberMovedRight);

BigDecimal bdNumberMovedLeft = bdNumberMovedRight.movePointLeft(2);
System.out.println("bdNumberMovedLeft: " + bdNumberMovedLeft);

Assertions.assertThat(bdNumberMovedLeft).isEqualTo(bdNumber);
}
``````

here's a couple of random results that seem satisfying:

``````string: 062533.74
bdNumberMovedRight: 6253374
bdNumberMovedLeft: 62533.74
string: 882297.73
bdNumberMovedRight: 88229773
bdNumberMovedLeft: 882297.73
string: 638429.50
bdNumberMovedRight: 63842950
bdNumberMovedLeft: 638429.50
string: 500882.06
bdNumberMovedRight: 50088206
bdNumberMovedLeft: 500882.06
string: 922547.94
bdNumberMovedRight: 92254794
bdNumberMovedLeft: 922547.94
``````