I am dealing with different numerical values. But, I want specific digit decimal values. What will be the solution for this?
Apr 13, 2018 in Java 1,385 views

You can use setRoundingMode() method to get n digit decimal values.

To write a solution for this question, you have to import 3 libraries.

```import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Arrays;

```

After importing these libraries, write the statements given below.

```public static void main(String[] args) {

DecimalFormat df = new DecimalFormat("#.##");

df.setRoundingMode(RoundingMode.CEILING);

for (Number n : Arrays.asList(15.00000, 13.23456)) {

Double d = n.doubleValue();

System.out.println(df.format(d));

}
}

```

Output will be:

15
13.24

• 4,630 points
`new BigDecimal(String.valueOf(double)).setScale(yourScale, BigDecimal.ROUND_HALF_UP);`

will get you a BigDecimal. To get the string out of it, just call that BigDecimal's toStringmethod, or the toPlainString method for Java 5+ for a plain format string.

Sample program:

```package trials;
import java.math.BigDecimal;

public class Trials {

public static void main(String[] args) {
int yourScale = 10;
System.out.println(BigDecimal.valueOf(0.42344534534553453453-0.42324534524553453453).setScale(yourScale, BigDecimal.ROUND_HALF_UP));
}```
• 59,230 points

How to round a number to n decimal places in Java?

Use setRoundingMode, set the RoundingMode explicitly to handle your issue ...READ MORE

How to round a double to 2 decimal places?

double value = 200.3456; System.out.printf("Value: %.2f", value); You can ...READ MORE

From Java 1.5 you can use the String.format method. ...READ MORE

How can we display an output of float data with 2 decimal places in java? Please help

You can use DecimalFormat. One way to use ...READ MORE

How can I convert a String variable to a primitive int in Java

Here are two ways illustrating this: Integer x ...READ MORE

+1 vote

How to generate random integers within specific range in Java?

You can achieve that concisely in Java: Random ...READ MORE

How to divide a string in two parts

String s="yourstring"; boolean flag = true; for(int i=0;i<s.length();i++) { ...READ MORE

Integer to String conversion in java

We can do this in 2 ways: String ...READ MORE