Rounding doubles to the nearest whole number in Java?

How do I round my numbers of output += Math.pow(baseUno, powernumber)+ " "; to the nearest whole number?

They always give me an output of, for example, 1.0 or 2.0. How do you round these so that they would simply result as 1 and 2?

import javax.swing.*;
import java.text.*;
import java.util.*;

public class level7Module1
{

public static void main(String[] args)
{

String base, power, output = " "; //user inputs, and the output variable
double baseUno, powerUno, basenum = 0, powernum = 0; //user inputs parsed so they can be used in mathematical equations

DecimalFormat noDigits = new DecimalFormat("0");

 // oneDigit.format(variablename)


base = JOptionPane.showInputDialog(null,"Enter your prefered base, a number between 1 and 14: nPress 'q' to quit."); //User input
    if (base.equals("q"))
    {
    JOptionPane.showMessageDialog(null,"Goodbye!");
    System.exit(0); //quits
    }

baseUno = Integer.parseInt(base);
// basenum = noDigits.format(baseUno);

if (baseUno <= 0)
{
JOptionPane.showMessageDialog(null,"Really? Why would you try to trick me? ):");
System.exit(0);
}
if (baseUno > 14)
{
JOptionPane.showMessageDialog(null,"That wasn't cool. Take some time to think about this nandnthenntrynagain.nnnnnnnnJerk.");
System.exit(0);
}

//I chose 0 and 14 because on my monitor the combination of 14 and 14 filled up the entire screen, so I limited to things
 //that would fit on my monitor :)

power = JOptionPane.showInputDialog(null, "How many numbers of this base would you like? Between 1 and 14 again, please.nPress 'q' to quit.");

if (power.equals("q"))
    {
    JOptionPane.showMessageDialog(null,"Goodbye!");
    System.exit(0);
    }

powerUno = Integer.parseInt(power);
// powernum = noDigits.format(powerUno);

if (powerUno <= 0)
    {
    JOptionPane.showMessageDialog(null,"Really? Why would you try to trick me? ):");
    System.exit(0);
    }
if (powerUno > 14)
    {
    JOptionPane.showMessageDialog(null,"That wasn't cool. Take some time to think about this nandnthenntrynagain.nnnnnnnnJerk.");
    System.exit(0);
    }

for (int powernumber=0; powernumber!=powerUno; powernumber++) //Set the number of powers done to 0, then until it's "powernum" input, it keeps going.
{
output += Math.pow(baseUno, powernumber)+ " "; //Output is the basenum to the power of powernum plus a space, then repeats condition above.
}

JOptionPane.showMessageDialog(null,"Your numbers are: " + output); //Giving the users their outputs

}
}

Answer

To the simplest approach change this line :
JOptionPane.showMessageDialog(null,"Your numbers are: " + output);
to
JOptionPane.showMessageDialog(null,"Your numbers are: " + (int)output);
just type caste the result to int

Leave a Reply

Your email address will not be published. Required fields are marked *