You can do this with a combination of DecimalFormat and < a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#parseDouble(java.lang.String)"> Double.parseDouble () . I created a custom Double called FormattedDouble that extends DecimalFloat to accomplish what you want. See the class code:
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
public class FormattedDouble extends DecimalFormat {
private static final long serialVersionUID = 1L;
private DecimalFormatSymbols symbols;
private String stringValue;
private double value;
public FormattedDouble(double value) {
super("#.##"); // Customize the format here.
symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator('.');
symbols.setGroupingSeparator(' ');
setDecimalFormatSymbols(symbols);
this.setStringValue(format(value));
this.setValue(Double.parseDouble(this.getStringValue()));
}
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
public String getStringValue() {
return stringValue;
}
public void setStringValue(String stringValue) {
this.stringValue = stringValue;
}
}
This, getting a Double with the number of houses limited (Using the example you gave), is simple:
public class Main {
public static void main(String[] args) {
double example = new FormattedDouble(3.1412233).getValue(); // Returns 3.14.
System.out.println(example); // Outputs 3.14.
}
}
You can adapt the FormattedDouble class to allow changes in the number of houses. Read the DecimalFormat documentation to be able to adapt to your needs.
EDIT:
It's not exactly what you want because it's not possible. A Double is a Double, and period (If you want to change the format , need format ). It is possible to simulate what you want, change at the "reading time", creating a custom Double as I did.