2011-12-26 3 views
4

У меня есть код Java GUI для вычисления диапазона данных, например, если введены два значения 2.444 и 3.555, результат будет длинным двойным 1.11100000... и т. Д. Как указать, сколько цифры после десятичной точки, которые она должна отображать? (Например: %.2f)Java: указание количества чисел после десятичной точки

Это мой код:

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); 
    } 
} 

ответ

8

Вы можете использовать String.format, чтобы определить выход вам нравится, например,

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

показать 4 десятичные знаки.

+0

является это утверждение будет отображать результат в gui? –

+0

Этот метод возвращает строковое представление, поэтому вы можете заменить код внутри 'showMessageDialog'. – Howard

3

DecimalFormat. Ниже пример формы here

import java.text.DecimalFormat; 
import java.text.NumberFormat; 

public class DecimalFormatExample 
{ 
    public static void main(String[] args) 
    { 
     // We have some millons money here that we'll format its look. 
     double money = 100550000.75; 

     // By default to toString() method of the Double data type will print 
     // the money value using a scientific number format as it is greater 
     // than 10^7 (10,000,000.00). To be able to display the number without 
     // scientific number format we can use java.text.DecimalFormat wich 
     // is a sub class of java.text.NumberFormat. 

     // Below we create a formatter with a pattern of #0.00. The # symbol 
     // means any number but leading zero will not be displayed. The 0 
     // symbol will display the remaining digit and will display as zero 
     // if no digit is available. 
     NumberFormat formatter = new DecimalFormat("#0.00"); 

     // Print the number using scientific number format. 
     System.out.println(money); 

     // Print the number using our defined decimal format pattern as above. 
     System.out.println(formatter.format(money)); 
    } 
} 
+0

Thanx это сработало .. –

-1

добавить этот экземпляр DecimalFormat в верхней части метода:

DecimalFormat three = new DecimalFormat("0.000"); 

// or this. this will modify the number to have commas every new thousandths place. 
DecimalFormat three = new DecimalFormat("#,##0.000"); 

// the three zeros after the decimal point above specify how many decimal places to be accurate to. 
// the zero to the left of the decimal place above makes it so that numbers that start with "0." will display "0." vs just "." If you don't want the "0.", replace that 0 to the left of the decimal point with "#" 

затем вызовите этот экземпляр и передать его строку при отображении:

String str = 4.651681351; 
display.setText(three.format(str)); // displays 4.652 
Смежные вопросы