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 ?
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 ?
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
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
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