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
  • 60,889
  • 18
  • 128
  • 171
Arianule
  • 8,811
  • 45
  • 116
  • 174

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
  • 12,974
  • 3
  • 37
  • 62
3
double d = 3.12345;

DecimalFormat newFormat = new DecimalFormat("#.###");
double twoDecimal =  Double.valueOf(newFormat.format(d));
Massimiliano Peluso
  • 26,379
  • 6
  • 61
  • 70
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
  • 283,665
  • 25
  • 256
  • 373
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
  • 525,659
  • 79
  • 751
  • 1,130