Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

# Thread: Better ways to round floats and/or doubles?

1. ## Better ways to round floats and/or doubles?

Hi. I'm trying to figure out how to round floating point numbers with more flexibility than just rounding to integers or rounding to two decimal places.

Here is the class with my methods:
```package samsExperiments;

public class Shapes {

double circumference = 2 * Math.PI * radius;
return circumference;
}
return circleArea;
}

}```

And here is the class that calls them:
```package samsExperiments;

import java.util.Scanner;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Vector;
import java.util.Hashtable;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Random;

import static exercises.StaticMethodExample.*;

import java.lang.StringBuilder;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Map;

import customExceptions.IntegerOutOfRangeException;

public class SamsExperimentsMain {

public static void main(String[] args){

Shapes shape = new Shapes();
System.out.println("The area of the our circle is " + (Math.round(circleArea*100.0)/100.0) + " square inches, "
+ "and the perimeter is " + circleCircumference + " inches.");

}//end of main method

}//end of class```

The output is:
The area of the our circle is 176.71 square inches, and the perimeter is 47.12388980384689 inches.

This is fine, but I want more control. For example, are there any round tools out there that look something like "round(circleCircumference,4)", which would give me 47.1238 for the circleCircumference variable in my output?

2. ## Re: Better ways to round floats and/or doubles?

Instead of rounding, why not use System.printf() with a format specifier. Check out the Java API to see more.

Regards,
Jim

3. ## The Following User Says Thank You to jim829 For This Useful Post:

SamJava_the_Hut (April 17th, 2019)

4. ## Re: Better ways to round floats and/or doubles?

Thanks Jim, it works

```//how to control the how many numbers are to the right of a decimal point:
double roundMe = 176.71458676442586;
System.out.printf("Our shortened double is now: %.4f\n", roundMe);//cut down to 4 digits after decimal point```