Reputation: 32331
I was working on a task where I was struck handling a negative scenario mentioned below
If the Value is less than 1 then I want to format (add) 4 decimal points to it .
For example if value is 0.4567 then I need 0.4567
Or else if the value is greater than 1 format with only 2 digits.
For example if value is 444.9 then I need 444.90
Everything above mentioned is working fine, but struck on this below condition
That is if the value is less than 1 and it ends as zeros (0.1000 , 0.6000) , It makes no sense to print 0.2000, so in that case I want the output to be only as 0.20
This is my program below
package com;
import java.text.DecimalFormat;
public class Test {
public static void main(String args[]) {
try {
String result = "";
Test test = new Test();
double value = 444.9;
if (value < 1) {
result = test.numberFormat(value, 4);
} else {
result = test.numberFormat(value, 2);
}
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}
public String numberFormat(double d, int decimals) {
if (2 == decimals)
return new DecimalFormat("#,###,###,##0.00").format(d);
else if (0 == decimals)
return new DecimalFormat("#,###,###,##0").format(d);
else if (3 == decimals)
return new DecimalFormat("#,###,###,##0.000").format(d);
else if (4 == decimals)
return new DecimalFormat("#,###,###,##0.0000").format(d);
return String.valueOf(d);
}
}
Upvotes: 6
Views: 5349
Reputation: 22271
Just make a string with four digits and check for trailing zeros. If there are two zeros or less, remove them. Otherwise, leave it as it is.
result = test.numberFormat(value, 4);
if (result.endsWith("00")) {
result=result.substring(0, result.length()-2);
} else if (result.endsWith("0")) {
result=result.substring(0, result.length()-1);
}
It may not be optimal, but it's easy to read and maintain.
Upvotes: 0
Reputation: 2896
use # if you want to ignore 0 in 3rd and 4th decimal places
new DecimalFormat("#,###,###,##0.00##").format(d)
Upvotes: 6