2

Good afternoon

Would just like to know what the easiest way would be of rounding a value of to a certain number of decimal places in Java.

With C#.

double answer;
double numberOne;
double numberTwo;
Console.WriteLine("Enter the numbers for your calculation");

numberOne = Double.Parse(Console.ReadLine());
numberTwo = Double.Parse(Console.ReadLine());
answer = numberOne / numberTwo;

Console.WriteLine(answer);
Console.WriteLine(Math.Round(answer, 3));

Kind regards

Matthew Farwell
  • 59,707
  • 18
  • 122
  • 168
Arianule
  • 8,483
  • 42
  • 111
  • 165

4 Answers4

4

Well, I guess

(double)Math.round(answer * 1000) / 1000;

would do the trick. There might be other options though!

Edit: Just found this thread for a more detailed discussion:

How to round a number to n decimal places in Java

Community
  • 1
  • 1
Willem Mulder
  • 11,762
  • 3
  • 34
  • 59
3
double d = 3.12345;

DecimalFormat newFormat = new DecimalFormat("#.###");
double twoDecimal =  Double.valueOf(newFormat.format(d));
Massimiliano Peluso
  • 25,679
  • 6
  • 57
  • 68
3

Look into using either a DecimalFormat object or String.format(...). For example

  double foo = 3.14159265;

  // note that printf uses the same formatter as Formatter 
  //as does String.format(...)
  System.out.printf("%.3f%n", foo);

  DecimalFormat dFormat = new DecimalFormat("0.###");
  System.out.println(dFormat.format(foo));
Hovercraft Full Of Eels
  • 280,125
  • 25
  • 247
  • 360
0

A faster way to round (provided the number is not too large)

double d = (long)(x > 0 ? x * 1000 + 0.5 : x * 1000 - 0.5)/1e3;

Its about 3x faster than using Math.round (but will fail for numbers greater than 9 million trillion ;)

Peter Lawrey
  • 513,304
  • 74
  • 731
  • 1,106