How to format a number into a fixed-length, space padded on left string with space as thousand seperator with 2 decimal places in Java? (let's say 14 characters string)
I.e.
Number = 10.03 must be: " 10.03"
and
Number = 1235353.93 must be " 1 235 353.93".
The %. 2f syntax tells Java to return your variable (value) with 2 decimal places (. 2) in decimal representation of a floating-point number (f) from the start of the format specifier (%).
Using the format() method "%. 2f" denotes 2 decimal places, "%. 3f" denotes 3 decimal places, and so on.
%d means number. %0nd means zero-padded number with a length. You build n by subtraction in your example. %s is a string. Your format string ends up being this: "%03d%s", 0, "Apple"
Use the String. format() method to pad the string with spaces on left and right, and then replace these spaces with the given character using String. replace() method. For left padding, the syntax to use the String.
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setGroupingSeparator(' ');
DecimalFormat format = new DecimalFormat("#,###.00", symbols);
System.out.format("%14s\n", format.format(1235353.93));
System.out.format("%14s\n", format.format(10.03));
The above prints below on my machine:
1 235 353.93
10.03
You can also use String.format
if you want to store the result into a variable:
String formatted = String.format("%14s", format.format(1235353.93));
System.out.println("Formatted Number is " + formatted);
However, if you weren't bothered about using (space) as the grouping separator, you could've simply done this:
String.format("%,14.2f", 234343.34);
Which would print:
234,343.34
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With