No, there is no better way.
Actually you have an error in your pattern. What you want is:
DecimalFormat df = new DecimalFormat("#.00");
Note the "00", meaning exactly two decimal places.
If you use "#.##" (# means "optional" digit), it will drop trailing zeroes - ie new DecimalFormat("#.##").format(3.0d); prints just "3", not "3.00".
java - How to convert a double to a string with 2 decimal places? - Stack Overflow
java - Round a double to 2 decimal places - Stack Overflow
java - How do I format a double into a string (with only two decimal places)? - Stack Overflow
java - Double.toString with two decimals - Stack Overflow
How can I control the number of decimal places when converting a double to a string in Java?
What's the difference between using String.valueOf() and Double.toString() when converting a double to a string in Java?
What happens when a double is converted to a string using the Double.toString() method and the double is Double.NaN or Double.POSITIVE_INFINITY?
No, there is no better way.
Actually you have an error in your pattern. What you want is:
DecimalFormat df = new DecimalFormat("#.00");
Note the "00", meaning exactly two decimal places.
If you use "#.##" (# means "optional" digit), it will drop trailing zeroes - ie new DecimalFormat("#.##").format(3.0d); prints just "3", not "3.00".
An alternative is to use String.format:
double[] arr = { 23.59004,
35.7,
3.0,
9
};
for ( double dub : arr ) {
System.out.println( String.format( "%.2f", dub ) );
}
output:
23.59
35.70
3.00
9.00
You could also use System.out.format (same method signature), or create a java.util.Formatter which works in the same way.
Example.setText(String.format("%.2f", dValue));
.2means 2 decimal placesfmeans it's a decimal type
The quick and dirty way is to use a formatted String and specify the number of decimal points. Lately there's been a trend of suggesting the usage of a DecimalFormat instead since it will respect different locales and the usage of commas or points as a decimal separator.
//The suggested way lately
DecimalFormat formatter = new DecimalFormat("#0.00");
twoDecimals.setText(formatter.format(2.123145));
//The usual way with some caveats
twoDecimals.setText(String.format("%.2f",2.123));
I'm pretty sure it could also be done with formatted strings, but hey.. who am I to go against the trend.
Here's an utility that rounds (instead of truncating) a double to specified number of decimal places.
For example:
Use with AIround(200.3456, 2); // returns 200.35
Original version; watch out with this
Use with AIpublic static double round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
long factor = (long) Math.pow(10, places);
value = value * factor;
long tmp = Math.round(value);
return (double) tmp / factor;
}
This breaks down badly in corner cases with either a very high number of decimal places (e.g. round(1000.0d, 17)) or large integer part (e.g. round(90080070060.1d, 9)). Thanks to Sloin for pointing this out.
I've been using the above to round "not-too-big" doubles to 2 or 3 decimal places happily for years (for example to clean up time in seconds for logging purposes: 27.987654321987 -> 27.99). But I guess it's best to avoid it, since more reliable ways are readily available, with cleaner code too.
So, use this instead
(Adapted from this answer by Louis Wasserman and this one by Sean Owen.)
Use with AIpublic static double round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
BigDecimal bd = BigDecimal.valueOf(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}
Note that HALF_UP is the rounding mode "commonly taught at school". Peruse the RoundingMode documentation, if you suspect you need something else such as Bankers’ Rounding.
Of course, if you prefer, you can inline the above into a one-liner:
new BigDecimal(value).setScale(places, RoundingMode.HALF_UP).doubleValue()
And in every case
Always remember that floating point representations using float and double are inexact.
For example, consider these expressions:
Use with AI999199.1231231235 == 999199.1231231236 // true
1.03 - 0.41 // 0.6200000000000001
For exactness, you want to use BigDecimal. And while at it, use the constructor that takes a String, never the one taking double. For instance, try executing this:
Use with AISystem.out.println(new BigDecimal(1.03).subtract(new BigDecimal(0.41)));
System.out.println(new BigDecimal("1.03").subtract(new BigDecimal("0.41")));
Some excellent further reading on the topic:
- Item 48: "Avoid
floatanddoubleif exact answers are required" in Effective Java (2nd ed) by Joshua Bloch - What Every Programmer Should Know About Floating-Point Arithmetic
If you wanted String formatting instead of (or in addition to) strictly rounding numbers, see the other answers.
Specifically, note that round(200, 0) returns 200.0. If you want to output "200.00", you should first round and then format the result for output (which is perfectly explained in Jesper's answer).
If you just want to print a double with two digits after the decimal point, use something like this:
Use with AIdouble value = 200.3456;
System.out.printf("Value: %.2f", value);
If you want to have the result in a String instead of being printed to the console, use String.format() with the same arguments:
Use with AIString result = String.format("%.2f", value);
Or use class DecimalFormat:
Use with AIDecimalFormat df = new DecimalFormat("####0.00");
System.out.println("Value: " + df.format(value));
Replace Double.toString() with only double value like below:
String formattedNumber = String.format(Locale.US, "%.2f", fluid24Hours);
Or from Java 8 use formatter like below:
NumberFormat formatter = DecimalFormat.getInstance(Locale.US);
formatter.setMaximumFractionDigits(2);
String formattedNumber = formatter.format(fluid24Hours);
double d1 = 123456.78;
double d2 = 567890;
Locale fmtLocale = Locale.getDefault(Category.FORMAT);
NumberFormat formatter = NumberFormat.getInstance(fmtLocale);
formatter.setMaximumFractionDigits(2);
formatter.setMinimumFractionDigits(2);
System.out.println(formatter.format(d1));
System.out.println(formatter.format(d2));
System.out.println(fmtLocale.toLanguageTag());
Format your double value to formated string using DecimalFormat.
String priceString = new DecimalFormat("$##.##").format(price);
Output -
$15.50
You can format by using BigDecimal:
double value= 255.956666;
BigDecimal bd = new BigDecimal(value).setScale(2, RoundingMode.HALF_UP);
System.out.println("value=" + bd);