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);
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);
You want to print 150.23
without the period. Formatting is not supposed to achieve that. You have to:
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.
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);
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