So I'm trying to write a program:
Print a number in scientific notation with 3 significant digits (e.g., 0.000838423 = 8.34*10^4).
You must define and use a module that rounds a number to a specified number of decimal places.

Here is what I've got so far:

public class Sn
{
	public static double round(double a, int dec)
	{
		a = a * (10^(dec));
		a = a + .5;
		int b = a;
		b = b / (10^(dec));
		return b;
	}
	
	public static void main(String[] args)
	{
		System.out.println("input the number");
		double a = IO.readDouble();
		
		double f = a;
		int c = 0;
		
		while (f < 1)
		{
			f = f * 10;
			c = c + 1;
		}
		
		System.out.println(round(f, 3) + "^" + c);	
	}
}

When I try to compile the program, it's reading a "possible loss of precision" error in module round(). Specifically, it's not letting me convert the double a to int b.

My logic behind round() is:

round(7.99384, 3)

7993.84 = 7.99384 + 10^(3)
7994.34 = 7993.84 + .5

by converting the double to an int:
7994.34 = 7994

7994 / 10^(3) =

7.994.

My logic behind main() is:

input = .0002342

f = .0002342 * 10 = .002342
c = 0 + 1 = 1

f = .002342 * 10 = .02342
c = 1 + 1 = 2

f = .02342 * 10 = .2342
c = 2 + 1 = 3

f = .2342 * 10 = 2.342
c = 3 + 1 = 4


My question is : How would I convert the [double a] to [int b]?

*** I can only use commands [for, while, if/else, elseif, dowhile]. IO.java is a module we were provided with to read inputs, among other things (returning errors, etc.)***

Edited 5 Years Ago by ilikepaste: n/a

how long I can't see old good assemler rounding method

a = a + .5;

but rounding Double value in Jave should be

public class Round {

    public static double roundTo2Places(double value) {
        assert value >= Long.MIN_VALUE / 100 && value <= Long.MAX_VALUE / 100;
        long digits = (long) (value < 0 ? value * 100 - 0.5 : value * 100 + 0.5);
        return (double) digits / 100;
    }

    private Round() {
    }
}
This question has already been answered. Start a new discussion instead.