Skip to content

Instantly share code, notes, and snippets.

@gayanvirajith
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gayanvirajith/0c6f39131724019d6f6a to your computer and use it in GitHub Desktop.
Save gayanvirajith/0c6f39131724019d6f6a to your computer and use it in GitHub Desktop.
Format decimal value into two decimal in swing
/**
* Format decimal value into two decimal in swing
* @author: Gayan Virajith
* @url: webcreate.lk
* @email: gayanvirajith@gmail.com / webcreatelk@gmail.com
*/
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.text.DecimalFormat;
/**
* DecimalDeom.java -
* Format decimal value into two decimal in swing
*/
class DecimalDemo extends JFrame{
/**
* label - Label to hold decimal number
*/
JLabel label;
/**
* salery - Decimal value of salery
*/
double salery = 20000.9922343;
/**
* Default constructor
*
* I used contructor to initialize the frame titles,size,close operation,etc.
* On this method you would see how format is going on...
*
*/
public DecimalDemo()
{
// Set frame title
setTitle("Decimal Demo");
// Set close operation
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// A variable to hold salery in string format
// getSaleryInFomrmatMethodOne() method will return string format of sallery.
// You can use getSaleryInFomrmatMethodTwo() also.
String saleryInText = getSaleryInFomrmatMethodOne();
// Initilaize the label
label = new JLabel(saleryInText);
// Add lable into the panel
getContentPane().add(label);
// Set the size of the jframe
setSize(200,200);
// Finally show up
setVisible(true);
}
/**
* getSaleryInFomrmatMethodOne() - format the decimal salery value into two decimals
* Used DateFormater class to format the deciamal value
* @return String - formatted salery
*/
public String getSaleryInFomrmatMethodOne() {
DecimalFormat df = new DecimalFormat("#.##");
return df.format(salery);
}
/**
* getSaleryInFormatMethodTwo () - format the decimal salery value into two decimals
* This time I used String.format() method
* @return String - formatted salery
*/
public String getSaleryInFormatMethodTwo() {
return String.format("%.2f", salery);
}
/**
* Main method
*/
public static void main(String []args)
{
// Create instance of the class, which would automatically rendered on your screen.
new DecimalDemo();
}
}
@gayanvirajith
Copy link
Author

Decimal demo

Steps to compile & run:

Go to your terminal (Command prompt on windows). Make your javac is working.

Compile

javac DecimalDemo.java

Run

java DecimalDemo

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment