1

I want to create a String from a double value with 10 character for example

Double d = 150.23;

The output string like this 0000015023+

I have used this code but it is not working:

String imponibile = String.format("%10d%n", myDoubleValue);
Manos Nikolaidis
  • 21,608
  • 12
  • 74
  • 82
bircastri
  • 2,169
  • 13
  • 50
  • 119
  • Possible duplicate of [Java: how to parse double from regex](http://stackoverflow.com/questions/3681242/java-how-to-parse-double-from-regex) – techfly May 11 '17 at 11:38
  • @Aenadon OP wants to print the number not parse it. Which means the `regex` at the title is quite misleading. I will edit it out. – Manos Nikolaidis May 11 '17 at 12:02

2 Answers2

2

You want to print 150.23 without the period. Formatting is not supposed to achieve that. You have to:

  1. transform the double number to a int number with the desired rounding and print the int:

    int i = (int) Math.round(100.0 * d);
    String.format("%010d", i)
    

    Where "010" means print at least 10 digits and pad with zero if there are less. The padding char going before the number of digits.

  2. print the double and remove the period from the string afterwards:

    String.format("%011.2f", d).replace(".", "")
    

    Note how you now have to specify 11 including the period. And you have to specify the number of digits after the period

I don't think there is a way to print the sign after a number with String.format. You can easily require to print it at the start which is the normal way to print numbers:

String s = String.format("%+010d", i);

And if you must you can use substring and concatenation to put it at the end:

String imponibile = s.substring(1) + s.charAt(0);
Manos Nikolaidis
  • 21,608
  • 12
  • 74
  • 82
0

Try f instead of d:

String imponibile = String.format("%010.0f", myDoubleValue*100);

Floating Point - may be applied to Java floating-point types: float, Float, double, Double, and BigDecimal Class Formatter

Yevhen Danchenko
  • 1,039
  • 2
  • 9
  • 17