Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Specifying how many numbers after the decimal point

I have a GUI Java code for calculating the range of data for example if two values entered 2.444 and 3.555 the result will be a long double 1.11100000... etc. How do I specify how many digits after the decimal point it should display? (ex: %.2f)

This is my code:

public class Range
{
    public static void main(String args[])
    {
        int num=0; //number of data
        double d; //the data
        double smallest = Integer.MAX_VALUE;
        double largest = Integer.MIN_VALUE;
        double range = 0;

        String Num =
        JOptionPane.showInputDialog("Enter the number of data ");
        num=Integer.parseInt(Num);

        for(int i=0; i<num; i++)    
        {
            String D =
            JOptionPane.showInputDialog("Enter the data ");
            d=Double.parseDouble(D);

            if(d < smallest)
                smallest = d;
            if(d > largest)
                largest = d; 
        }

        range = largest - smallest ; //calculating the range of the input

        JOptionPane.showMessageDialog(null,"Range = "+smallest+"-"+largest+" = "+range,"Range",JOptionPane.PLAIN_MESSAGE);
    }
}
like image 986
Aisha S Avatar asked Dec 21 '22 04:12

Aisha S


1 Answers

You can use String.format to define the output you like, e.g.

String.format("Range = %.4f", range)

to show 4 decimal places.

like image 192
Howard Avatar answered Jan 04 '23 22:01

Howard