-1

I need to print a Double as a String but I don't know how many decimal places there will be and I have to be prepared for as many as possible. Right, now I'm using this ugly solution:

Double dubs = 0.000157;

NumberFormat formatter = new DecimalFormat(
    "##.########################################################################################");
System.out.println(formatter.format(dubs));
ArcticDoom
  • 64
  • 6

3 Answers3

1

You can do this with no conversion:

public class codesnippets {

 public static void main(String[] args)
 {
     Double dubs = 0.000157;
     System.out.printf("%f", dubs);
 }

}

You can also use

Double dubs = 0.000157;
String dubs_format = String.format("%f", dubs);
System.out.println(dubs);

EDIT: Apparently there is a precision loss when using "%f" as a format string. If this is the case for you, use "%.10f"

Steampunkery
  • 3,839
  • 2
  • 19
  • 28
0

Try here man. I think this is what you're saying. The answer given at the bottom.

Number of decimal digits in a double

Here is what I meant.

double d= 234.12413;
String text = Double.toString(Math.abs(d));
int integerPlaces = text.indexOf('.');
int decimalPlaces = text.length() - integerPlaces - 1;

Then you just concatenate them

String xmlString = integerPlaces.toString() + "." + decimalPlaces.toString();
Sinil
  • 87
  • 10
0

This seemed to work based on Steampunkery's idea. The catch was that I needed an actual String which I realize I wasn't clear on.

String dubString= String.format("%f", dubs); 
System.out.println(dubString);
ArcticDoom
  • 64
  • 6