Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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".
like image 488
Rinus Avatar asked Feb 21 '12 10:02

Rinus


People also ask

How do you do 2 decimal places in Java?

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 (%).

How do you set decimal places in Java?

Using the format() method "%. 2f" denotes 2 decimal places, "%. 3f" denotes 3 decimal places, and so on.

What is %d and %s in Java?

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

How do I format string spacing in Java?

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.


1 Answers

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
like image 141
adarshr Avatar answered Oct 10 '22 01:10

adarshr