Double
doesn't have any concept of maintaining insignificant digits.
The problem isn't the Double
(or double
) value you're using - it's how you then convert it back into a string. You should use a DecimalFormat
which specifies the appropriate number of decimal places.
Also note that you're currently using Double.parseDouble
which returns a double
, but you're assigning it to a Double
variable, which will box the value - potentially unnecessarily.
Sample code:
import java.text.DecimalFormat;
public class Test {
public static void main(String[] args) {
String text = "500.00";
double number = Double.parseDouble(text);
DecimalFormat format = new DecimalFormat("0.00");
String formatted = format.format(number);
System.out.println(formatted);
}
}
Note that the above code will give you two decimal digits even if there are more digits available.
Additionally, if exact decimal digits matter to you, you might want to consider using BigDecimal
instead of double
. This is particularly important if your values actually represent currency. You should understand the difference between a floating binary point type (such as double
) and a floating decimal point type (such as BigDecimal
) and choose appropriately between them.