Java : Removing zeros after decimal point in BigDecimal
Simple, clean, flexible, easy-2-understand and maintain code
(will work for double
too)
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2); //Sets the maximum number of digits after the decimal point
df.setMinimumFractionDigits(0); //Sets the minimum number of digits after the decimal point
df.setGroupingUsed(false); //If false thousands separator such ad 1,000 wont work so it will display 1000
String result = df.format(bd);
System.out.println(result);
try this
import java.math.BigDecimal;
import java.text.DecimalFormat;
public class calculator{
public static void main(String[] args) {
BigDecimal bd = new BigDecimal(23.086);
BigDecimal bd1= new BigDecimal(0.000);
DecimalFormat df = new DecimalFormat("0.##");
System.out.println("bd value::"+ df.format(bd));
System.out.println("bd1 value::"+ df.format(bd1));
}
}
Let's say you have BigDecimal with value 23000.00
and you want it to be 23000
. You can use method stripTrailingZeros()
, but it will give you "wrong" result:
BigDecimal bd = new BigDecimal("23000.00");
bd.stripTrailingZeros() // Result is 2.3E+4
You can fix it by calling .toPlainString()
and passing this to the BigDecimal constructor to let it handle correctly:
BigDecimal bd = new BigDecimal("23000.00");
new BigDecimal(bd.stripTrailingZeros().toPlainString()) // Result is 23000