Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java decimal formatting using String.format?

I need to format a decimal value into a string where I always display at lease 2 decimals and at most 4.

So for example

"34.49596" would be "34.4959"  "49.3" would be "49.30" 

Can this be done using the String.format command?
Or is there an easier/better way to do this in Java.

like image 841
richs Avatar asked Jan 11 '09 23:01

richs


2 Answers

Yes you can do it with String.format:

String result = String.format("%.2f", 10.0 / 3.0); // result:  "3.33"  result = String.format("%.3f", 2.5); // result:  "2.500" 
like image 77
mostar Avatar answered Sep 18 '22 19:09

mostar


You want java.text.DecimalFormat.

DecimalFormat df = new DecimalFormat("0.00##"); String result = df.format(34.4959); 
like image 25
Richard Campbell Avatar answered Sep 21 '22 19:09

Richard Campbell