Rinus
Rinus

Reputation: 99

How to format a number to Fixed length, space padded, thousand separator, 2 decimals in Java

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

Upvotes: 8

Views: 10859

Answers (3)

Evan Siroky
Evan Siroky

Reputation: 9438

If you're doing this to format currency, it's more robust to use locales:

Locale uslocale = new Locale.Builder().setLanguage("en").setRegion("US").build();
NumberFormat.getCurrencyInstance(uslocale).format(payment);

Upvotes: 0

adarshr
adarshr

Reputation: 62613

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

Upvotes: 19

Alexander Pavlov
Alexander Pavlov

Reputation: 32306

Give a try to String#format() - its format string should let you do what you need.

Upvotes: 0

Related Questions