3

I'm currently using the method :

String.format("%.4", myDouble);

The trouble with this is that if I get a number with less decimals, such as 2.34, it will display 2.3400 . Is there a way to avoid that ?

sh5164
  • 276
  • 2
  • 15
  • 2
    Use `DecimalFormat` to format decimals... – Codebender Oct 26 '15 at 15:49
  • If you are talking about a percentage or using this in a scientific context, it might be clearer to write them all with the same number of decimals. For example, if it's exactly 2.3400% and the next number is 5.8794%, then the former should be written as 2.3400. Here, the zeroes are significant. – rajah9 Oct 26 '15 at 15:58
  • 1
    http://stackoverflow.com/questions/11701399/round-up-to-2-decimal-places-in-java – Reimeus Oct 26 '15 at 16:01

3 Answers3

4

Using DecimalFormat and pattern #.#### should work. It will display up to 4 digits after the decimal point but it might be less if no need.

See http://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html

Gaël J
  • 11,274
  • 4
  • 17
  • 32
2

You can use Math.round function :) example:

Math.round(192.15515452*10000)/10000.0

returns 192.1551

and Math.round(192.15*10000)/10000.0

returns 192.15

Shivam
  • 649
  • 2
  • 8
  • 20
1

Use DecimalFormat and a pattern.

double value = 2.34;
String pattern = "#.####";
DecimalFormat myFormatter = new DecimalFormat(pattern);
String output = myFormatter.format(value);

System.out.println(value + " " + pattern + " " + output);  // displays  2.34 #.#### 2.34

For more references Customizing Formats

Dimitri
  • 1,906
  • 3
  • 25
  • 49