Jason
Jason

Reputation: 12789

How do I format a decimal value to have appropriate amount of trailing spaces

I have a double value which could be either 9.2 or 13.45 or 198.789 or 110.8. How do I format this to 9.2000 or 13.4500 198.7890 or 110.8000

Upvotes: 0

Views: 784

Answers (6)

rodion
rodion

Reputation: 15029

You can use String.format() to some extent. For example:

String.format("%07.3f", 1.23d); //prints 001.230

The format is %0<width>.<precision>f where, <width> is the minimum number of character (including the dot) that should be printed padded with 0's (in my example there are 7 characters); <precision> is the number of digits after the decimal point.

This method will work for simple formatting, and you cannot control the rounding (rounding is is half-up by default).

Upvotes: 0

user467871
user467871

Reputation:

Have a look at DecimalFormat

Upvotes: 1

pinichi
pinichi

Reputation: 2205

new DecimalFormat("#0.0000").format(9.2); //"9.2000"

Upvotes: 2

trickwallett
trickwallett

Reputation: 2468

See: The DecimalFormat Class under

http://download.oracle.com/javase/tutorial/java/data/numberformat.html

Upvotes: 1

Jim
Jim

Reputation: 22656

Look into the Decimal Format class.

Upvotes: 2

npinti
npinti

Reputation: 52205

This SO post can be of help.

Upvotes: 4

Related Questions