Pregunta

Say for example that I have the Double value 1.23456789123456. I want to be able to multiply this number by various powers of 10 and display the output as

  123.456789123456
12345.6789123456
    0.0123456789123456
    0.000123456789123456
etc

Is there any way to do this in Java without having to use if...then statements to handle the changing decimal precision required for different powers of 10?

¿Fue útil?

Solución

This could be improved, but it's close:

public class Test {

    public static void main(final String[] args) {
        System.out.println(format(123.456789123456d));
        System.out.println(format(12345.6789123456d));
        System.out.println(format(0.0123456789123456d));
        System.out.println(format(0.000123456789123456d));
    }

    public static String format(final double d) {
        final int before = 16 - Integer.toString((int) d).length();
        final String format = "%" + (16 + before) + "." + before + "f";
        return String.format(format, d);
    }

Output:

        123.4567891234560
      12345.67891234560
          0.012345678912346
          0.000123456789123

Otros consejos

If you don't need the number as an actual floating point value, try representing the number as a String without a decimal point (e.g., "123456789123456"). Then using the String.substring() method, you can print the decimal point wherever you want, include leading zeroes, etc. I don't know that you can totally avoid using any if statements, but the logic should be fairly straightforward.

For instance, this prints the decimal after three significant digits:

String n = "123456789123456";
System.out.print(n.substring(0, 3));
System.out.print('.');
System.out.print(n.substring(3));

Check out the DecimalFormat class

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top