How to pad numbers with underscores in Java, instead of the usual zeros ?
For example I want
I tried lots of stuff and closest I got was this (by using SYMBOLS.setZeroDigit('_');):
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
public class Example {
    public static void main(String[] args) {
        DecimalFormatSymbols SYMBOLS = new DecimalFormatSymbols();
        SYMBOLS.setDecimalSeparator('.');
        SYMBOLS.setGroupingSeparator(',');
        DecimalFormat OUTPUT_FORMAT = new DecimalFormat("000,000.00", SYMBOLS);
        System.out.println(OUTPUT_FORMAT.format(0.01));
        // got 000,000.01
        System.out.println(OUTPUT_FORMAT.format(0.12));
        // got 000,000.12
        System.out.println(OUTPUT_FORMAT.format(123456));
        // got 123,456.00
        System.out.println(OUTPUT_FORMAT.format(123456.78));
        // got 123,456.78
        System.out.println(OUTPUT_FORMAT.format(1234));
        // got 001,234.00
        System.out.println(OUTPUT_FORMAT.format(1234.56));
        // got 001,234.56
        SYMBOLS.setZeroDigit('_');
        OUTPUT_FORMAT = new DecimalFormat("000,000.00", SYMBOLS);
        System.out.println(OUTPUT_FORMAT.format(0.01));
        // expected ______._1 but got ___,___._`
        System.out.println(OUTPUT_FORMAT.format(0.12));
        // expected ______.12 but got ___,___.`a
        System.out.println(OUTPUT_FORMAT.format(123456));
        // expected 123,456.__ but got `ab,cde.__
        System.out.println(OUTPUT_FORMAT.format(123456.78));
        // expected 123,456.78 but got `ab,cde.fg
        System.out.println(OUTPUT_FORMAT.format(1234));
        // expected __1,234.00 or at least __1,234.__ but got __`,abc.__
        System.out.println(OUTPUT_FORMAT.format(1234.56));
        // expected __1,234.56 but got __`,abc.de
    }
}
Well, not really close but an empty number if formated right (with trailing underscores): ___,___.__
Anyway, suggestions on how to get the expected behaviour?
"_________".substring( num.length() )+num;
where num is a String holding your number. To convert a double to a String, you can use Double.toString(myDouble).
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