Feb 5, 2009

Forcing double into specified decimal place

import java.text.*;
import javax.swing.*; // All the methods that belong to the class Swing are imported

public class TestFoodItem
{
public static void main(String args[])
{
String output = "";
String foodName = "";
String foodWeight = "";
String foodPrice = "";
foodName = JOptionPane.showInputDialog( "What you bought?" );
foodWeight = JOptionPane.showInputDialog( "Enter the weight of the item?" );
Float f = new Float(foodWeight); // First Convert the weight from string to float
double weigh = f.doubleValue(); // Then Convert the float to double

foodPrice = JOptionPane.showInputDialog( "Enter the price of the item?");
Float g = new Float(foodPrice); // First Convert the weight from string to float
double price = g.doubleValue(); // Then Convert the float to double


FoodItem MyShopping = new FoodItem(foodName, weigh, price);

output = "Description of the item: " + MyShopping.getDesc() + "\n";
output = output + "weight of the item: " + MyShopping.getWeight() + "\n";
output = output + "Price per kg $ " + MyShopping.getPrice() + "\n";
output = output + "Total Price of the item $:" + MyShopping.calcTotalPrice() + "\n";
JOptionPane.showMessageDialog( null, output, MyShopping.getDesc(), JOptionPane.INFORMATION_MESSAGE);

// forcing decimal place to two digits
DecimalFormat df = new DecimalFormat("#0.00");
//df.setMinimumFractionDigits(2);
output = "";
output = "Description of the item: " + MyShopping.getDesc() + "\n";
output = output + "weight of the item: " + MyShopping.getWeight() + "\n";
String formatedPrice = df.format(MyShopping.calcTotalPrice());
output = output + "Price per kg $ " + formatedPrice + "\n";
String formatedTotalPrice = df.format(MyShopping.calcTotalPrice());
output = output + "Total Price of the item $:" + formatedTotalPrice + "\n";
JOptionPane.showMessageDialog( null, output, MyShopping.getDesc(), JOptionPane.INFORMATION_MESSAGE);







}
}

No comments:

Down with the Dictatorship!

    "Let them hate me, so that they fear me" - Caligula 41AD