My requirement is that if the last variable value is less than 1 for example 0.0045
then i need to print 4 digits after the decimals so that the result will look like 0.0045
or else if the last variable value is greater than 1 for example 444.8183
then i need to print only 2 digits after the decimals so that the result will look like 444.82
I have written the program , its working fine , but i like to use the ternary opearator
public class Test {
private static NumberUtil numberUtil = NumberUtil.getInstance();
public static void main(String args[]) {
float last = (float) 444.8183;
String result = "";
if (last > 1) {
result = numberUtil.formatNumber(last, 2);
} else {
result = numberUtil.formatNumber(last, 4);
}
System.out.println(result);
}
}
import java.text.DecimalFormat;
public class NumberUtil {
private static NumberUtil _instance = new NumberUtil();
public static NumberUtil getInstance() {
return _instance;
}
public String formatNumber(double d, int decPts) {
if (2 == decPts)
return new DecimalFormat("#,###,###,##0.00").format(d);
else if (0 == decPts)
return new DecimalFormat("#,###,###,##0").format(d);
else if (3 == decPts)
return new DecimalFormat("#,###,###,##0.000").format(d);
else if (4 == decPts)
return new DecimalFormat("0.0000").format(d);
return String.valueOf(d);
}
public double formatDoubleNumber(double d){
double newD = Math.round(d*100.0)/100.0;
return newD;
}
}