How to Truncate a Double to Only Two Decimal Places in Java

How can I truncate a double to only two decimal places in Java?

If you want that for display purposes, use java.text.DecimalFormat:

 new DecimalFormat("#.##").format(dblVar);

If you need it for calculations, use java.lang.Math:

 Math.floor(value * 100) / 100;

How to truncate double to N decimal places?

"in particular to avoide the expensive conversion to String and back" - This is exactly what avoids the loss of precision. You can't get arbitrary precision for free.

If you need arbitrary precision then you should not use double but instead do:

static String truncate(String value, int places) {
return new BigDecimal(value)
.setScale(places, RoundingMode.DOWN)
.stripTrailingZeros()
.toString()
}

Truncate double numbers to two decimal places using DecimalFormat: Usage of API documented as @since 1.6+ error

double number = 2.90689;
DecimalFormat df = new DecimalFormat("#.00");
df.setRoundingMode(RoundingMode.FLOOR); //error
System.out.println(df.format(number));

Please check https://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html

0   Number  Yes Digit
# Number Yes Digit, zero shows as absent

round up to 2 decimal places in java?

Well this one works...

double roundOff = Math.round(a * 100.0) / 100.0;

Output is

123.14

Or as @Rufein said

 double roundOff = (double) Math.round(a * 100) / 100;

this will do it for you as well.

Round a double to 2 decimal places

Here's an utility that rounds (instead of truncating) a double to specified number of decimal places.

For example:

round(200.3456, 2); // returns 200.35

Original version; watch out with this

public 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.)

public 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:

999199.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:

System.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 float and double if 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).

Best way to Format a Double value to 2 Decimal places

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".

Truncate number to two decimal places without rounding

Convert the number into a string, match the number up to the second decimal place:

function calc(theform) {    var num = theform.original.value, rounded = theform.rounded    var with2Decimals = num.toString().match(/^-?\d+(?:\.\d{0,2})?/)[0]    rounded.value = with2Decimals}
<form onsubmit="return calc(this)">Original number: <input name="original" type="text" onkeyup="calc(form)" onchange="calc(form)" /><br />"Rounded" number: <input name="rounded" type="text" placeholder="readonly" readonly></form>

How do I round a double to two decimal places in Java?

Are you working with money? Creating a String and then converting it back is pretty loopy.

Use BigDecimal. This has been discussed quite extensively. You should have a Money class and the amount should be a BigDecimal.

Even if you're not working with money, consider BigDecimal.



Related Topics



Leave a reply



Submit