I need to give accuracy of a number entered by user till few digit. like if user enter some random value and gives that he wants accuracy till three digit then I need to rou
You can indeed use NumberFormat to do this
double amount = 15;
NumberFormat formatter = new DecimalFormat("#0.000");
System.out.println("The Decimal Value is:"+formatter.format(amount));
you can use string format:
Double area = 6
String ar = String.format("%.3f", area); ar = 6.000
You can create a method that returns the exact format for your decimals. Here is an example:
public String formatNumber(int decimals, double number) {
StringBuilder sb = new StringBuilder(decimals + 2);
sb.append("#.");
for(int i = 0; i < decimals; i++) {
sb.append("0");
}
return new DecimalFormat(sb.toString()).format(number);
}
If you don't need to change the decimals
value so often, then you can change your method to something like:
public DecimalFormat getDecimalFormat(int decimals) {
StringBuilder sb = new StringBuilder(decimals + 2);
sb.append("#.");
for(int i = 0; i < decimals; i++) {
sb.append("0");
}
return new DecimalFormat(sb.toString());
}