Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pad numbers with underscore in Java?

How to pad numbers with underscores in Java, instead of the usual zeros ?

For example I want

  • 123.45 to be formated to ___123.45 and
  • 12345.67 to be formated to _12345.67
  • 0.12 to be formated to ______.12

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?

like image 452
Belun Avatar asked Aug 04 '11 17:08

Belun


1 Answers

"_________".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).

like image 123
tskuzzy Avatar answered Sep 25 '22 00:09

tskuzzy