1
votes

I am creating a DOUBLE variable that will always be in the format 0.xxx. While I want the three decimal digits to appear each time, I do not want to see the leading zero (eg: .275). I have found many ways to remove the leading zero in a STRING, but not using a DOUBLE variable.

To give more detail, I am dividing one int by another int to get the double. I am able to use printf/ .3f to get to the thousandths position, but %0.3f results in an error. I must be missing something simple, but have failed to find my error.

3
some code would be great.. - Ashim
When you display it, it will always be a String, sometimes hidden. Why not make it explicit and remove the leading zeros then? - AntonH

3 Answers

2
votes

You can use DecimalFormat class. Something like :

System.out.println(new DecimalFormat(".###").format(x));
1
votes

It looks like using DecimalFormat works:

import java.text.DecimalFormat;

public class DecimalPrintNoZero
{
  public static void main(String[] args)
  {
    double d = 0.275;
    DecimalFormat df = new DecimalFormat("#.000");
    System.out.println(df.format(d));
  }
}

References:

http://developer.android.com/reference/java/text/DecimalFormat.html

Java - Format number to print decimal portion only

0
votes

Decimal format will work

public class DoublePrinter {
public static void main(String[] args) {
    Double d = 0.325;
    DecimalFormat format = new DecimalFormat("0.000");
    Double price2 = Double.parseDouble(format.format(d));
    System.out.println(price2);

    String s = format.format(d);
    System.out.println("s is '" + s + "'");
}

}