-1

I was looking for a simple way to round a double value to 10 digits but I didn't found even one way that look good to me, everything was too complicated. I hope someone could help me, for example: the value 0.83426945721236485 will become 0.8342694572

Thank you in advance.

Noah Levy
  • 69
  • 1
  • 7

2 Answers2

3

Simple.

DecimalFormat df = new DecimalFormat("0.0000000000");
System.out.println(df.format(0.83426945721236485));

Take a look at the documentation: https://docs.oracle.com/javase/8/docs/api/java/text/DecimalFormat.html

Sina Madani
  • 1,246
  • 3
  • 15
  • 27
  • 1
    But I can't see how it rounds an already given value, looks like you just print a number on the screen. – Noah Levy May 12 '16 at 22:02
  • You're right. I spent the past 10 mins trying to come up with a primitive way to do rounding but couldn't find a short way without some nasty string concatenation and parsing. – Sina Madani May 12 '16 at 22:31
0

Decimal places are not meaningful internally for double, because it is a binary floating point.

You can, of course, choose to display it in any format supported by DecimalFormat, as suggested in a prior answer.

If you want a ten decimal place internal representation, you should be using BigDecimal with scale factor 10.

Community
  • 1
  • 1
Patricia Shanahan
  • 25,849
  • 4
  • 38
  • 75