📅  最后修改于: 2023-12-03 15:15:55.883000             🧑  作者: Mango
When working with floating point numbers in Java, it's often necessary to convert them to a string format for various purposes such as display, input/output, or serialization. In this tutorial, we will show you how to convert a Double to a String with 2 decimal places in Java.
One common way to convert a Double to a formatted String in Java is to use the DecimalFormat class. This class provides a simple way to format a number based on a set of predefined patterns. Here's an example:
double number = 123.456789;
DecimalFormat df = new DecimalFormat("#.00");
String formatted = df.format(number);
System.out.println(formatted); // "123.46"
In the example above, we create a DecimalFormat object with the pattern #.00
which specifies that we want to display the number with 2 decimal places. We then call the format
method to convert the double value to a formatted string.
Another way to perform this conversion in Java is to use the String.format
method. This method allows us to apply formatting directly to a string using placeholders. Here's an example:
double number = 123.456789;
String formatted = String.format("%.2f", number);
System.out.println(formatted); // "123.46"
In the example above, we use the %f
placeholder to specify that we want to display the double value with 2 decimal places. The %.2f
format string tells Java to display the double value rounded to 2 decimal places.
Another approach to convert a Double to a String with 2 decimals is to use the BigDecimal class. This class provides a more precise way to work with floating point numbers in Java, but can be slower than DecimalFormat or String.format. Here's an example:
double number = 123.456789;
BigDecimal bd = new BigDecimal(number);
bd = bd.setScale(2, RoundingMode.HALF_UP);
String formatted = bd.toString();
System.out.println(formatted); // "123.46"
In the example above, we first create a BigDecimal object based on the double value. We then use the setScale
method to specify that we want to round the number to 2 decimal places using the RoundingMode.HALF_UP
rounding mode. Finally, we use the toString
method to convert the BigDecimal object to a String.
There are several ways to convert a Double to a String with 2 decimal places in Java. Depending on your use case, you may find one approach to be more suitable than the others. In this tutorial, we've shown you how to use DecimalFormat, String.format, and BigDecimal to perform this conversion.