0

So say for instance i have the following code:

    DecimalFormat df = new DecimalFormat();
    df.setMaximumFractionDigits(2);
    df.setMinimumFractionDigits(2);
    df.format(125,436573);  

Now this returns a string.

Since you cannot convert String into a double (using cast) how would i get a type double?

Also as far as i oculd understand this only removes everything after the two digits instead of actually rounding up.

I have been looking around the Java.lang.math objects but couldnt seem to find the solution

For the record i need it to insert the double it into my database table.

Marc Rasmussen
  • 19,771
  • 79
  • 203
  • 364

3 Answers3

2

This is what I use to round to two decimal places.

public static double round2(double d) {
    final double factor = 1e2;
    return d > Long.MAX_VALUE / factor || d < -Long.MAX_VALUE / factor ?
            (long) (d < 0 ? d * factor - 0.5 : d * factor + 0.5) / factor : d;
}

You don't need to produce a String just so you can parse it back again.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • 1
    Upvoted because elegant, correct answer but mostly because this is the longest ternary operation I have seen in a return statement. – nook Jun 12 '13 at 04:05
  • 1
    @publ1c_stat1c lol it is pretty ugly, but you can see exactly what it does. – Peter Lawrey Jun 12 '13 at 10:31
1

This is an example where I am not sure the question you are asking is the question you really want to pose. It seems as if you want to have decimals with exactly two decimal places, but not just a question of final output format, but for persistence.

You don't want to do this with doubles. You will get round-off errors because decimals can not be stored exactly in binary notation. And you don't want to store money as doubles in your database for the same reason. (Link, link, link)

As you can see in the links there, you want to be using some combination of integers with an implied decimal point, or BigDecimal, or NUMERIC fields in the database.

Community
  • 1
  • 1
Andrew Lazarus
  • 18,205
  • 3
  • 35
  • 53
0

You can use commons-math3 Precision.round(double x, int scale)

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275