# Rounding in Java

**URL:** <https://boards.straightdope.com/t/rounding-in-java/81398>\
**Category:** Factual Questions\
**Created:** [September 13, 2001, 6:02pm UTC](https://boards.straightdope.com/t/rounding-in-java/81398 "2001-09-13T18:02:55Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![Studi](https://avatars.discourse-cdn.com/v4/letter/s/5daacb/32.png) [@Studi](https://boards.straightdope.com/u/Studi)\
**Post date:** [September 13, 2001, 6:02pm UTC](https://boards.straightdope.com/t/rounding-in-java/81398/1 "2001-09-13T18:02:55Z")

</div>

How would I round a large number in scientific notation from, for example, 4.33453453453453E15 to 4.33E15?

Yes, this is for school. A hint/suggestion would be appreciated.

Studi

---

<div class="post-metadata">

**Author:** ![Punoqllads](https://avatars.discourse-cdn.com/v4/letter/p/d2c977/32.png) [@Punoqllads](https://boards.straightdope.com/u/Punoqllads)\
**Post date:** [September 13, 2001, 7:09pm UTC](https://boards.straightdope.com/t/rounding-in-java/81398/2 "2001-09-13T19:09:40Z")

</div>

> [@](#):
>
> \*Originally posted by Studi \*  
> \*\*How would I round a large number in scientific notation from, for example, 4.33453453453453E15 to 4.33E15?
> 
> Yes, this is for school. A hint/suggestion would be appreciated.
> 
> Studi \*\*

Do you need to round it for doing further calculations, or are you only wanting to round it for the sake of printing it out?

If it’s the latter, think about writing a routine that only prints out the digits that you need. If it’s the former, think about adding or subtracting the “right” amount to make it a round number.

---

<div class="post-metadata">

**Author:** ![Studi](https://avatars.discourse-cdn.com/v4/letter/s/5daacb/32.png) [@Studi](https://boards.straightdope.com/u/Studi)\
**Post date:** [September 13, 2001, 10:03pm UTC](https://boards.straightdope.com/t/rounding-in-java/81398/3 "2001-09-13T22:03:24Z")

</div>

Yeah, it only needs to be printed out.

What kind of routine?

Studi

---

<div class="post-metadata">

**Author:** ![Studi](https://avatars.discourse-cdn.com/v4/letter/s/5daacb/32.png) [@Studi](https://boards.straightdope.com/u/Studi)\
**Post date:** [September 14, 2001, 3:33pm UTC](https://boards.straightdope.com/t/rounding-in-java/81398/4 "2001-09-14T15:33:55Z")

</div>

Yes, this is a bump.

Does the Math.round method have to be used?

Someone help! We’re all so confused!

Studi

---

<div class="post-metadata">

**Author:** ![erislover](https://avatars.discourse-cdn.com/v4/letter/e/71e660/32.png) [@erislover](https://boards.straightdope.com/u/erislover)\
**Post date:** [September 14, 2001, 5:33pm UTC](https://boards.straightdope.com/t/rounding-in-java/81398/5 "2001-09-14T17:33:37Z")

</div>

You certainly could use Math.round after a little foolin’ with the digits.

For example, you could turn 1.23456E7 into 123.456E5, then use Math.round, and then return the exponent to normal.

simple enough, really.

Float temp = number; (number here is the variable which currently stores the result)  
int sigFigs = 3; (or however many significant digits you want)  
int exponent = Math.exp(10, sigFigs);  
temp \*= exponent;  
temp = Math.round(temp);  
temp /= exponent;  
number = temp;

There might be a less intesive way to do it, but that should work (if I have the exponent method correct, it might be Math.pow(#, exp))

I’d try it myself but my java compiler is at home and I am not.

---

<div class="post-metadata">

**Author:** ![Studi](https://avatars.discourse-cdn.com/v4/letter/s/5daacb/32.png) [@Studi](https://boards.straightdope.com/u/Studi)\
**Post date:** [September 14, 2001, 6:29pm UTC](https://boards.straightdope.com/t/rounding-in-java/81398/6 "2001-09-14T18:29:59Z")

</div>

Thanks **Erislover** , but the code you gave doesn’t work for large numbers (numbers in sci.notation). At least, not the way I have it.

I appreciate the work, though.

Yes, I’m a beginner with Java. Someone please help!

Studi

---

<div class="post-metadata">

**Author:** ![tulley](https://avatars.discourse-cdn.com/v4/letter/t/d07c76/32.png) [@tulley](https://boards.straightdope.com/u/tulley)\
**Post date:** [September 14, 2001, 6:34pm UTC](https://boards.straightdope.com/t/rounding-in-java/81398/7 "2001-09-14T18:34:28Z")

</div>

I believe what you’re looking for is DecimalFormat, a java object which lets you specify how many significant digits you want to view. The documentation is at [http://java.sun.com/j2se/1.3/docs/api/index.html](http://java.sun.com/j2se/1.3/docs/api/index.html)

This should do what you want. If it doesn’t, you can always dump the number into a string and format the length manually. Its ugly but it works.

---

<div class="post-metadata">

**Author:** ![Studi](https://avatars.discourse-cdn.com/v4/letter/s/5daacb/32.png) [@Studi](https://boards.straightdope.com/u/Studi)\
**Post date:** [September 14, 2001, 8:23pm UTC](https://boards.straightdope.com/t/rounding-in-java/81398/8 "2001-09-14T20:23:49Z")

</div>

Thanks, **Tulley** , but that is too confusing for a beginner like me.

And I thought about converting to strings, but I’m not able to, considering this assignment is to learn about Java mathematics.

Studi

---

<div class="post-metadata">

**Author:** ![The\_Great\_Gazoo](https://avatars.discourse-cdn.com/v4/letter/t/67e7ee/32.png) [@The\_Great\_Gazoo](https://boards.straightdope.com/u/The_Great_Gazoo)\
**Post date:** [September 14, 2001, 8:33pm UTC](https://boards.straightdope.com/t/rounding-in-java/81398/9 "2001-09-14T20:33:57Z")

</div>

I think Erislover has it, but maybe backwards.

I think you need to divide the number by some factor (say you have 3,212,365,234,455 - you need to divide this by 10,000,000 to get it down to 321.2365234455 - then use the round function to round it to 321 - then multiply it by 10,000,000 and it will be 3,210,000,000,000 - which would then be 3.21e9 (or whatever - I didn’t watch my decimal points too carefully here)

---

<div class="post-metadata">

**Author:** ![erislover](https://avatars.discourse-cdn.com/v4/letter/e/71e660/32.png) [@erislover](https://boards.straightdope.com/u/erislover)\
**Post date:** [September 15, 2001, 1:27am UTC](https://boards.straightdope.com/t/rounding-in-java/81398/10 "2001-09-15T01:27:06Z")

</div>

Hmm… I see a Math.exp(double) method, which returns a double…

All the other methods seem pretty self-explanitory, but I can’t see what this does. I’m gonna screw with it and get back to you.

---

<div class="post-metadata">

**Author:** ![erislover](https://avatars.discourse-cdn.com/v4/letter/e/71e660/32.png) [@erislover](https://boards.straightdope.com/u/erislover)\
**Post date:** [September 15, 2001, 2:06am UTC](https://boards.straightdope.com/t/rounding-in-java/81398/11 "2001-09-15T02:06:27Z")

</div>

Suprisingly, I found no method to get the E number from any arbitrary double.

You could use  
Double.toString(number)  
to get a string, then manipulate the string in any number of ways, then return it to a number.

Alternatively you can write a loop to find the exponent like so:

```auto

public class Test {
    public static void main(String[] args) {

    double number = 1.2345E76;
    double temp = number;
    int sigFigs = 3; // number of significant digits
    int exp = 0;
    System.out.println(number);
    //the max E for a double is 309
    for (int i = 0; i < 310; i++) {
    // following loop sets exp = the E value
    // and removes it
        if (temp / 10 > 1) {
            temp /= 10;
            exp++;
            }
        }
    temp *= Math.pow(10, sigFigs);
    temp = Math.round(temp);
    temp *= Math.pow(10, exp - sigFigs);
    number = temp;
    System.out.println(number);
    }
}

```

---

<div class="post-metadata">

**Author:** ![erislover](https://avatars.discourse-cdn.com/v4/letter/e/71e660/32.png) [@erislover](https://boards.straightdope.com/u/erislover)\
**Post date:** [September 15, 2001, 2:09am UTC](https://boards.straightdope.com/t/rounding-in-java/81398/12 "2001-09-15T02:09:40Z")

</div>

I should mention two things. One, I am learning Java as we speak, though I’m teaching myself so this was as much an excersize for me as it was to help you. Two, I did test this and it does work. I tried to make it flexible enough with variables so you can edit and change what you need to work into the rest of the program.

---

<div class="post-metadata">

**Author:** ![Studi](https://avatars.discourse-cdn.com/v4/letter/s/5daacb/32.png) [@Studi](https://boards.straightdope.com/u/Studi)\
**Post date:** [September 15, 2001, 6:55pm UTC](https://boards.straightdope.com/t/rounding-in-java/81398/13 "2001-09-15T18:55:00Z")

</div>

Okay, **erislover** , this is kind of working.

Basically, my programme gets a number from the user then performs some operations on it. The last is e^(x^2), where x is the number the user entered and e is the base of the natural logarithm. The result has to be rounded to three or four significant figures if the answer is in sci. notation (as it is for any number larger than around 5) and rounded to two decimal places otherwise. I’m going to set up a if/else structure. If x \> about 5, then it’ll use the code you just gave. If not (that is, if the number isn’t in sci.notation) I’ll use the Math.round method to round it (which is easy enough to do).

The code I have for that section of the programme is:

```auto

                double squared_x;
		double eTo_xSquared;
		squared_x = X * X;
		eTo_xSquared = Math.pow(Math.E,squared_x);
			
		if (X>5) {
			double number = eTo_xSquared; //
			double temp = number; //
			int sigFigs = 4; //
			int exp = 0; //
			// The max E for a double is 309
			for (int i = 0; i < 310; i++) { //
			//this loop sets exp to the E of the result
				if (temp/10 > 1) { //
					temp /= 10; //
					exp++; //
				} //
			} //
			temp *= Math.pow(10,sigFigs); //
			temp = Math.round(temp); //
			temp *= Math.pow(10,exp - sigFigs); //
			number = temp; //
			System.out.println("
The value of e to the exponent x squared is " + eTo_xSquared + ".");
			System.out.println("The value of e to the exponent x squared (rounded) is " + number + ".");
		}

		else {
			final double ROUND_TO = 0.01;
			double rounded_eTo_xSquared;
			rounded_eTo_xSquared = Math.round(eTo_xSquared/ROUND_TO) * ROUND_TO;		
			System.out.println("
The value of e to the exponent x squared is " + eTo_xSquared + ".");
			System.out.println("The value of e to the exponent x squared (rounded) is " + rounded_eTo_xSquared + ".");
		}

```

Everything you provided has a // after the line so I’ll be sure to sufficiently change it to my own code.

If you want to try this out, I guess you can makeup your own X. I’m going to toy with that if (X\>5) section to get a better value from which to switch rounding methods.

One other problem is that the code you provided, **erislover** isn’t working _quite_ perfectly. For example, it’s rounding 1.42436453452346245645E250 to 1.42440000000000000000001E250 when it should be 1.4244E250. I’ll try to figure out why.

Once again, thanks for all the help.

Studi

---

<div class="post-metadata">

**Author:** ![Studi](https://avatars.discourse-cdn.com/v4/letter/s/5daacb/32.png) [@Studi](https://boards.straightdope.com/u/Studi)\
**Post date:** [September 15, 2001, 7:03pm UTC](https://boards.straightdope.com/t/rounding-in-java/81398/14 "2001-09-15T19:03:39Z")

</div>

Okay, I got it working.

Thank you everyone for your help/suggestions.

Studi

---

<div class="post-metadata">

**Author:** ![erislover](https://avatars.discourse-cdn.com/v4/letter/e/71e660/32.png) [@erislover](https://boards.straightdope.com/u/erislover)\
**Post date:** [September 15, 2001, 7:06pm UTC](https://boards.straightdope.com/t/rounding-in-java/81398/15 "2001-09-15T19:06:48Z")

</div>

It didn’t do anything of the sort on my machine. Hmm, it sure does have something funny happening there…

---

<div class="post-metadata">

**Author:** ![erislover](https://avatars.discourse-cdn.com/v4/letter/e/71e660/32.png) [@erislover](https://boards.straightdope.com/u/erislover)\
**Post date:** [September 15, 2001, 7:08pm UTC](https://boards.straightdope.com/t/rounding-in-java/81398/16 "2001-09-15T19:08:11Z")

</div>

Dont go, I’m interested in what you changed…

---

<div class="post-metadata">

**Author:** ![Studi](https://avatars.discourse-cdn.com/v4/letter/s/5daacb/32.png) [@Studi](https://boards.straightdope.com/u/Studi)\
**Post date:** [September 15, 2001, 9:04pm UTC](https://boards.straightdope.com/t/rounding-in-java/81398/17 "2001-09-15T21:04:15Z")

</div>

Here’s my whole programme. For it to work, you’d need the Stdin.java file I have, which is not a part of ordinary Java. I guess you’ll have to take out that line near the top, and replace

```auto

final double X = Stdin.getDouble();

```

with the number you want to test.

```auto

class Calculations
{	
	public static void main (String[] args)
	{
		//x is saved as a constant double, as it should never be changed throughout the duration of this programme.

		System.out.println("This programme will carry out four mathematical operations for you.");	
		System.out.println("Please enter the value, x, you wish to work with:");	
		final double X = Stdin.getDouble();

		/*This section first finds the absolute value of x (thus making a negative x positive), and then finds the square root of this value. The absolute value and square root math methods are used.*/
		
		double absolute_x;
		double rooted_x;
		absolute_x = Math.abs(X);
		rooted_x = Math.sqrt(absolute_x);
		System.out.println("
The square root of the absolute value of x is " + rooted_x);
		/*This section first doubles the value of x, and converts it into radians (required by Java for trig. operations). This is done through the use of the Math.PI constant. Next, the application prints out the value of the 2x in degrees and radians. Then, the Math.sin method is used to find the sin value of 2x, and this is printed in a subsequent line.*/

		double two_x = 2*X;
		double radTwo_x;
		double sinRadTwo_x;
		radTwo_x = two_x * (Math.PI/180);
		System.out.println("
The value of " + two_x + " degrees in radians is " + radTwo_x + ".");
		sinRadTwo_x = Math.sin(radTwo_x);
		System.out.println("The value of sin(2x) is " + sinRadTwo_x + ".");
		/*This section utilises the Math.pow method to find the value of x to the exponent fifty. The result is then printed.*/

		double exponent50_x;
		exponent50_x = Math.pow(X,50);
		System.out.println("
The value of x to the exponent 50 is " + exponent50_x + ".");
		/*Here, x is squared without the use of the Math.pow method, as the magnitude of the exponent is rather small. Next, Math.pow is used to find the value of e to the exponent x squared, a more complex operation.*/

		double squared_x;
		double eTo_xSquared;
		squared_x = X * X;
		eTo_xSquared = Math.pow(Math.E,squared_x);
			
		/*The next section is fairly complex. Two different rounding methods are used. If the number is in scientific notation (which would happen if X>4.0145) one rounding method is used. If the number is not in scientific notation, the Math.round method is used. The Math.round method does not easily work for rounding the mantissa of a number in scientific notation to three (or four) significant figures.*/

		
		
		if (X>4.0145) {
			double round_eTo_xSquared, y = eTo_xSquared;
			int sFigures = 2;
			int exponent = 0;
			//The maximum E for a double is +309.
			for (int k = 0; k < 310; k++) {
			
				if (y/10 > 1) {
					y /= 10;
					exponent++;
				}
			}
			y *= Math.pow(10,sFigures);
			y = Math.round(y);
			y *= Math.pow(10,exponent - sFigures);
			round_eTo_xSquared = y;
			//System.out.println("
The value of e to the exponent x squared is " + eTo_xSquared + ".");
			System.out.println("
The value of e to the exponent x squared (rounded) is " + round_eTo_xSquared + ".");
		}

		else {
			final double ROUND_TO = 0.01;
			double rounded_eTo_xSquared;
			rounded_eTo_xSquared = Math.round(eTo_xSquared/ROUND_TO) * ROUND_TO;		
			//System.out.println("
The value of e to the exponent x squared is " + eTo_xSquared + ".");
			System.out.println("
The value of e to the exponent x squared (rounded) is " + rounded_eTo_xSquared + ".");
		}
	}
}

```

With the code you provided (which is in the last section), I basically just switched the number of significant figures to two.

Studi

---

<div class="post-metadata">

**Author:** ![douglips](https://avatars.discourse-cdn.com/v4/letter/d/e68b1a/32.png) [@douglips](https://boards.straightdope.com/u/douglips)\
**Post date:** [September 15, 2001, 9:40pm UTC](https://boards.straightdope.com/t/rounding-in-java/81398/18 "2001-09-15T21:40:45Z")

</div>

DecimalFormat is too confusing? I think learning about DecimalFormat is perhaps confusing at first, but using it is simple once you know how.

Here is an entire program which computes e^(x^2) for an X given on the command line, using the DecimalFormat class instead of a big old gyration to round it off.

```auto

import java.text.DecimalFormat;

public class foo
{

    private static void _exitUsageError()
    {
	System.err.println("Usage: java foo N.NNNN");
	System.exit(1);
    }

    public static void main (String[] args)
    {
	if (args.length < 1) {
	    _exitUsageError();
	}
	
	double X = 1.0;
	// Try to convert to a number.
	try {
	    X = Double.valueOf(args[0]).doubleValue();
	}
	catch (NumberFormatException e) {
	    _exitUsageError();
	}
	
	System.out.println("You entered:" + X);

	// Begin erislover's code
	double eTo_xSquared = Math.pow(Math.E, X*X);
	
	// Adjust number of #'s to change precision	
	DecimalFormat myFormat = new DecimalFormat("0.###E0");
	String formattedResult = myFormat.format(eTo_xSquared);

	System.out.println("
The value of e to the exponent x squared is " + eTo_xSquared + ".");
	System.out.println("The value of e to the exponent x squared (rounded) is " + formattedResult + ".");
    }
}

```

If you continue to do what you are doing, at least consider this step to calculate the exponent instead of that loop:

```auto

	int exponent = (int)(squared_x/Math.log(10));

```

This works because the integer part of log[sub]10/sub is the value you want, and log[sub]10/sub = ln(y)/ln(10). Since the number you care about is e[sup]x[sup]2[/sup][/sup], the ln is just x[sup]2[/sup].

---

<div class="post-metadata">

**Author:** ![dingleburg](https://avatars.discourse-cdn.com/v4/letter/d/a9a28c/32.png) [@dingleburg](https://boards.straightdope.com/u/dingleburg)\
**Post date:** [September 16, 2001, 4:17am UTC](https://boards.straightdope.com/t/rounding-in-java/81398/19 "2001-09-16T04:17:30Z")

</div>

or at least it should–who has the energy to debug anymore?

n=numberToBeScientificallyNotated;  
int i=0;  
String result;  
while (n\>10000)  
{  
n=n/10;  
i++;  
}  
n=n/1000;  
i=i+3;  
result=n+“E”+i;

---

<div class="post-metadata">

**Author:** ![dingleburg](https://avatars.discourse-cdn.com/v4/letter/d/a9a28c/32.png) [@dingleburg](https://boards.straightdope.com/u/dingleburg)\
**Post date:** [September 16, 2001, 2:08pm UTC](https://boards.straightdope.com/t/rounding-in-java/81398/20 "2001-09-16T14:08:57Z")

</div>

double n=numberToBeScientificallyNotated; //forgot to cast  
int i=0;  
String result;  
while (n\>10000)  
{  
n=n/10;  
i++;  
}  
n=Math.round(n); //forgot to drop the decimals  
n=n/1000;  
i=i+3;  
result=n+“E”+i;

minor adjustments would be needed for values of n smaller than 10000 and for values of n less than 1.
