Tuesday, February 27, 2018

BigDecimal to String :)

public static void main(String[] args) {
double d = 10.00001;
BigDecimal bigDecimal = new BigDecimal(d);
System.out.println(bigDecimal);
// result: 10.000009999999999621422830387018620967864990234375
System.out.println(bigDecimal.toPlainString());
// result: 10.000009999999999621422830387018620967864990234375
System.out.println(bigDecimal.toString());
// result: 10.000009999999999621422830387018620967864990234375
System.out.println(bigDecimal.stripTrailingZeros().toString());
// result: 10.000009999999999621422830387018620967864990234375
System.out.println(bigDecimal.stripTrailingZeros().toPlainString());
// result: 10.000009999999999621422830387018620967864990234375

DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
df.setMinimumFractionDigits(5);
df.setGroupingUsed(false);
String format = df.format(bigDecimal);
System.out.println(format);
// result: 10.00001
}


public static final String FORMAT_DEFAULT = "#0.00";
public static final NumberFormat formatter = new DecimalFormat(FORMAT_DEFAULT);

public static final String FormatDefault = "0.##";
public static final NumberFormat Formatter = new DecimalFormat(FormatDefault);

public static void main(String[] args) {

double d = 1000000.00001;
BigDecimal bigDecimal = new BigDecimal(d);
System.out.println(bigDecimal);

String format1 = formatter.format(d);
System.out.println(format1);

String format2 = Formatter.format(d);
System.out.println(format2);

}