Showing posts with label fahrenheit to celsius. Show all posts
Showing posts with label fahrenheit to celsius. Show all posts
Tuesday, February 12, 2013
Tutorial 13 : Java Formatting Double Value
Java Tutorial For Beginner, Tutorial 13 : Formatting Double Value
To format double value to 2 decimal format, use java.text.DecimalFormat class to format the display of leading and trailing zeros, prefixes and suffixes, grouping (thousands) separators, and the decimal separator.
In this example, to format to decimat format i use the following statements;
Step 1; Use the java.text.* to use java.text.DecimalFormat class
import javax.swing.JOptionPane;
Step 2: Create DecimalFormat object called dFormat, use to format 2 decimal point by using the pattern "#.##"
DecimalFormat dformat= new DecimalFormat("#.##");
Step 3 : Finally, use format() method to format the double value. It accepts double value as argument and returns a string.
dformat.format(celsius)
Code below :
// Celsius to Fahrenheit Converter Example
// How to format double value;
// Watch output without formatting value;
import javax.swing.JOptionPane;
// add this
import java.text.*;
public class Fahrenheit{
public static void main(String[] args){
String number = JOptionPane.showInputDialog(null, "Enter fahrenheit value : " , "Fahrenheit to Celsius Converter", JOptionPane.QUESTION_MESSAGE);
//convert string to number
double fahrenheit = Double.parseDouble(number);
double celsius = (5.0/9)*(fahrenheit- 32);
// Add this to format the double value
DecimalFormat dformat= new DecimalFormat("#.##");
// To produce, 2 decimal point output
JOptionPane.showMessageDialog(null, "Fahrenheit value is " + fahrenheit + "\n" + "Celcius value is " + dformat.format(celsius) ,
"Fahrenheit to Celsius", JOptionPane.INFORMATION_MESSAGE);
}
}
Subscribe to:
Posts (Atom)