Working with Precise Decimals

Im trying to work with a form that creates a precise decimal from two JTextareas into a 3rd JTextarea.

Eg

Produced Goods ——– 32746534

Spoiled Goods ——– 4756

Spoiled Percentage —— xx.xxxxxxxx%

It needs to be exact and work with 11 digit produced goods and 10 decimal point percentages.

.

BigDecimal d1 = new BigDecimal(Integer.parseInt(linerInfeedTextField.getText()));
                BigDecimal d2 = new BigDecimal(Integer.parseInt(shellsSPoiledTextField.getText()));

                BigDecimal d3 = d1.multiply(d2); // d1 + d2 is invalid
                BigDecimal d4 = d3.divide(new BigDecimal(100));

                percentSpoiledTextField.setText(d4+"%");

Answer

Use DecimalFormat..

Example:

DecimalFormat df = new DecimalFormat("###.####") // <- "###.###" specifies precision

double x = 143.13;
double y = 23.12;
double answer = x / y;

System.out.println("Answer: " + df.format(answer));

Leave a Reply

Your email address will not be published. Required fields are marked *