How do i change 2.278481... to 2.2?
double a = 180;
double b = 79;
double x = (a/b);
Math.ceil() returns 3 and Math.floor() returns 2
How do i change 2.278481... to 2.2?
double a = 180;
double b = 79;
double x = (a/b);
Math.ceil() returns 3 and Math.floor() returns 2
You can just set the setMaximumFractionDigits to 1. Like this:
public class Test {
public static void main(String[] args) {
System.out.println(format(14.0184849945)); // prints '14.0'
System.out.println(format(13)); // prints '13'
System.out.println(format(3.5)); // prints '3.5'
System.out.println(format(3.138136)); // prints '3.1'
}
public static String format(Number n) {
NumberFormat format = DecimalFormat.getInstance();
format.setRoundingMode(RoundingMode.FLOOR);
format.setMinimumFractionDigits(0);
format.setMaximumFractionDigits(1);
return format.format(n);
}
}
This may helps you
Try this:
public static String customFormat(String pattern, double value) {
NumberFormat nf = NumberFormat.getNumberInstance(Locale.ENGLISH);
DecimalFormat df = (DecimalFormat)nf;
df.applyPattern(pattern);
return df.format(value);
}
Calling:
double x = Double.parseDouble(customFormat("###.#", a/b);
This method does round up the numbers as well.
For the English locale:
, is not the decimal splitter. This is valid: ##,##,##,##.###
. is the decimal splitter. This is not valid: ##.##.##.##,###
(at least not for this locale)