The console is telling me it can't find the symbol "getCurrencyInstance()" when I know I properly imported java.text.NumberFormat
I removed some code so it wasn't quite as cluttered; this isn't my whole class.
import java.util.Scanner;
import java.text.NumberFormat;
public class Kohls
{
// initialization
static Prompter prompter;
static Calculator calc;
static Operator operator;
private enum cardColor
{
RED, BLUE, GREEN;
} // end of enum Color
private static class Calculator
{
public int getDiscount(int age, cardColor color)
{
if (age > 62)
// senior discount
return 20;
if (color == cardColor.RED)
{
return 30;
}
else if (color == cardColor.BLUE)
{
return 25;
}
else if (color == cardColor.GREEN)
{
return 15;
}
return 0;
}
public double getSalePrice(int discountPercentage, double price)
{
double salePrice = price - (price * (discountPercentage / 100));
return salePrice;
}
} // end of class Calculator
private class Operator
{
public void getPriceWithDiscount()
{
// prompts
double price = prompter.getPrice();
int age = prompter.getAge();
cardColor color = prompter.getColor();
// discount(s)
int discountPercentage = calc.getDiscount(age, color);
double salePrice = calc.getSalePrice(discountPercentage, price);
NumberFormat fmt = new NumberFormat.getCurrencyInstance();
String salePriceFormat = fmt.format(salePrice);
operator.display(discountPercentage, salePriceFormat);
}
public void display(int discountPercentage, String salePrice)
{
System.out.print("You saved " + discountPercentage + "% on your purchase.");
System.out.print("\nThe price of your purchase with discount is " + salePrice + ".");
}
} // end of class Operator
public Kohls()
{
prompter = new Prompter();
calc = new Calculator();
operator = new Operator();
} // end of constructor
public static void main(String[] args)
{
Kohls kohls = new Kohls();
kohls.operator.getPriceWithDiscount();
} // end of method main()
} // end of class Kohls
This is syntactically incorrect:
NumberFormat fmt = new NumberFormat.getCurrencyInstance();
You are not newing an instance of NumberFormat. NumberFormat.getCurrencyInstance() is a method call, and hence can't be newed.
Since the method already returns a static instance of NumberFormat, go ahead and drop the new keyword from the declaration:
NumberFormat fmt = NumberFormat.getCurrencyInstance();
Remove new operator in the line. It is a static method and should be accessed in a static away. More over, NumberFormat is an abstract class and you cannot instantiate it as well.
NumberFormat nf = NumberFormat.getCurrencyInstance();
Don't do
new NumberFormat.getCurrencyInstance();
for a static method. Do
NumberFormat.getCurrencyInstance();
This line
NumberFormat fmt = new NumberFormat.getCurrencyInstance();
should be
NumberFormat fmt = NumberFormat.getCurrencyInstance();
since getCurrencyInstance() is declared static.
Hope this helps.
You should not be using new as getCurrencyInstance() is static
Change
NumberFormat fmt = new NumberFormat.getCurrencyInstance();
to
NumberFormat fmt = NumberFormat.getCurrencyInstance();
Related
Below is the double return type function and i would like to get the answer with precision of 2 zeros. My current answer is coming out to be -4.5. Whereas i want it to be -4.50. Any kind of help will be really appreciated
public double getAmount(){
double ftotal = car.hello();
return Math.round(ftotal * 100)/100.0d;
}
The returned value is a Double so you can't pad 0s to a Double.
So you must format the returned value to create a string, like:
NumberFormat formatter = new DecimalFormat("#0.00");
String number = formatter.format(getTotal());
System.out.println(number);
Refer below code -
import java.text.DecimalFormat;
public class Decimal2{
private static DecimalFormat df2 = new DecimalFormat(".##");
public static void main(String[] args) {
double input = 62.123454;
System.out.println("double : " + df2.format(input));
}
}
I'm working out a question from a labsheet but i'm only getting 0.0 as answer when running the program. I can't find out what's wrong please help.
The question:
Implement a class Pizza with attribute diameter (in cm), cost_sq_cm (cost per square cm) and area. Its methods are:
• Constructor to create an object of type Pizza with a given diameter and given price_sq_cm.
• Mutator and accessor methods for diameter and cost_sq_cm.
• calcArea to calculate the area of a given pizza.
• getPrice to calculate and return the price of a pizza.
Write a class TestPizza with a main method that declares an object of type Pizza with a user inputted diameter and user-‐inputted cost_sq_cm of a circular pizza, and display the price of the pizza.
The Pizza class:
package Number3;
public class Pizza {
private int diameter;
private float cost_sq_cm;
private double area;
private double price;
public Pizza() //default constructor
{
diameter = 0;
cost_sq_cm = 0;
area = 0;
price = 0;
}
public Pizza(int d,float cost,double a,double p) //overloaded constructor
{
d = diameter;
cost = cost_sq_cm;
a = area;
p = price;
}
public void Constructor() //method
{
Pizza P = new Pizza();
}
public void setDiameter(int d) //mutator
{
d = diameter;
}
public int getDiameter() //accessor
{
return diameter;
}
public void setCost(float c)
{
c = cost_sq_cm;
}
public float getCost()
{
return cost_sq_cm;
}
public double calcArea()
{
area = 3.142 * (diameter * diameter);
return area;
}
public double getPrice()
{
price = area * cost_sq_cm;
return price;
}
public void display()
{
System.out.print("The area is: "+this.price);
}
}
TestPizza:
package Number3;
import java.util.Scanner;
public class TestPizza {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
float area = 0;
Pizza P = new Pizza();
int d; float c,a = 0;
System.out.print("Enter a value for the diameter: ");
d = input.nextInt();
P.setDiameter(d);
System.out.print("Enter a value for the cost: ");
c = input.nextFloat();
P.setCost(c);
P.display();
}
}
I'm new to JAVA. Please be lenient.
You should multiply cost per square centimeter times area to get price. You'll get zero if either one is equal to zero. I see where you've set diameter, but not area.
You set diameter, but you don't calculate area when you set it.
public void setDiameter(int d) //mutator; lose this comment. worthless clutter.
{
d = diameter;
area = calcArea();
}
I'd recommend following the Java idiom. Don't write a display() method; better to override toString().
I'd write it this way:
package cruft;
import java.text.DecimalFormat;
import java.text.NumberFormat;
/**
* Pizza
* #author Michael
* #link https://stackoverflow.com/questions/28658669/classes-and-objects-getting-0-0-as-answer-when-calculating-price-java
* #since 2/22/2015 12:27 PM
*/
public class Pizza {
private static final int DEFAULT_DIAMETER = 38;
private static final double DEFAULT_COST = 15.0;
private static final double DEFAULT_COST_PER_AREA = 0.013226; // 15 euro for a 38 cm diameter pizza
private static final NumberFormat DEFAULT_FORMAT = new DecimalFormat("#.####");
private final int diameter;
private final double costPerArea;
private final double price;
public static void main(String[] args) {
int diameter = ((args.length > 0) ? Integer.valueOf(args[0]) : DEFAULT_DIAMETER);
double costPerArea = ((args.length > 1) ? Double.valueOf(args[1]) : DEFAULT_COST_PER_AREA);
Pizza pizza = new Pizza(diameter, costPerArea);
System.out.println(pizza);
}
public Pizza(int diameter, double costPerArea) {
if (diameter <= 0) throw new IllegalArgumentException("diameter must be positive");
if (costPerArea <= 0) throw new IllegalArgumentException("cost per area must be positive");
this.diameter = diameter;
this.costPerArea = costPerArea;
this.price = this.costPerArea*this.calculateArea();
}
public double getPrice() {
return price;
}
private double calculateArea() {
return Math.PI*this.diameter*this.diameter/4.0;
}
#Override
public String toString() {
final StringBuilder sb = new StringBuilder("Pizza{");
sb.append("diameter=").append(diameter);
sb.append(", costPerArea=").append(DEFAULT_FORMAT.format(costPerArea));
sb.append(", price=").append(NumberFormat.getCurrencyInstance().format(getPrice()));
sb.append('}');
return sb.toString();
}
}
For setting a field or another value it is
variable = value;
so
diameter = d;
It looks like your setCost and setDiameter methods need to be changed,
From
d = diameter;
To
this.diameter = d;
Instead of:
System.out.print("The area is: "+this.price);
Use:
System.out.print("The area is: "+this.getPrice());
You need to calculate area as well. So in your main method call it like:
P.calcArea();//to calculate area
You initialised price as 0, when you called new Pizza() and you never called getPrice which is where you calculate the price.
Also change your setter for cost from:
public void setCost(float c) {
c = cost_sq_cm;
}
To
public void setCost(float c) {
cost_sq_cm = c;
}
I know this is homework so this may sound weird. Right now I am trying to get rid of a compile error saying pool must implement abstract methods. Pool is implemented by the BackYard interface, while deck is a subclass of pool and bollards is a subclass of deck. I am not allowed to change the code in the display output method in the driver class and I am not allowed to change code in deck or bollards. The compiler keeps insisting that I recode all the subclass methods in pool or make pool abstract which I can't do either. What exactly do I need to fix. Also let me know if I really needed to code all the get methods in the Backyard interface
Here is the driver class:
public class YardOrders
{
//Constants
final static int POOL_ONLY = 1;
final static int POOL_N_DECK=2;
final static int POOL_DECK_N_BOLLARD=3;
final static int DISPLAY_ORDERS=4;
final static int DEFAULT_INT=0;
//Methods
public static void main(String[] args)
{
int numberOfOrders=DEFAULT_INT;
BackYard backYard[] = new BackYard[100];
int selection = DEFAULT_INT;
do
{
selection = Integer.parseInt(JOptionPane.showInputDialog(null,
"Options:\nEnter "+ POOL_ONLY +" for a pool.\n" +
"Enter "+ POOL_N_DECK +
" for a pool and a concrete " +
"deck surrounding the pool.\n"+
"Enter "+POOL_DECK_N_BOLLARD+" for a pool," +
" deck, and bollards.\n"+
"Enter "+DISPLAY_ORDERS+" to display orders and exit.",
"Pool Options", JOptionPane.PLAIN_MESSAGE));
if(selection > DEFAULT_INT && selection < DISPLAY_ORDERS)
{
getPoolInput(backYard,numberOfOrders,selection);
numberOfOrders++;
System.out.println(numberOfOrders);
}
else if(selection==DISPLAY_ORDERS)
{
displayOrders(backYard,numberOfOrders);
System.out.println(numberOfOrders);
System.exit(DEFAULT_INT);
}
else
{
JOptionPane.showMessageDialog(null,"Invalid input. Values" +
" must be between 1 and 4.");
}
}while(selection != DISPLAY_ORDERS);
}
private static void getPoolInput(BackYard backYard[],int numberOfOrders,int selection)
{
//Pool attributes
String lastName = JOptionPane.showInputDialog(null,
"Enter last name.\n","Last Name",
JOptionPane.PLAIN_MESSAGE);
String firstName = JOptionPane.showInputDialog(null,
"Enter first name.","First Name",
JOptionPane.PLAIN_MESSAGE);
double poolDepth = Double.parseDouble(
JOptionPane.showInputDialog(null,
"Enter pool depth in inches.","Pool Depth",
JOptionPane.PLAIN_MESSAGE)); //In inches.
double poolDiameter = Double.parseDouble(
JOptionPane.showInputDialog(null,
"Enter pool diameter in feet.","Pool Diameter",
JOptionPane.PLAIN_MESSAGE));//In feet.
if(selection == POOL_ONLY)
{
//Pool instantiation.
backYard[numberOfOrders]= new Pool(lastName,firstName,
poolDepth,poolDiameter);
}
else
{
getDeckInput(backYard,
numberOfOrders,selection,
lastName,firstName,
poolDepth, poolDiameter);
}
}//End of method
private static void getDeckInput(BackYard[] backYard,
int numberOfOrders, int selection,
String lastName, String firstName,
double poolDepth, double poolDiameter)
{
//Deck attributes
double deckLength=Double.parseDouble(
JOptionPane.showInputDialog(null,
"Enter deck length in feet.","Deck Length",
JOptionPane.PLAIN_MESSAGE));
double deckWidth= Double.parseDouble(
JOptionPane.showInputDialog(null,
"Enter deck width in feet.","Deck Width",
JOptionPane.PLAIN_MESSAGE));
if(selection==POOL_N_DECK)
{
backYard[numberOfOrders]= new Deck(lastName,firstName,
poolDepth,poolDiameter,
deckLength,deckWidth);
}
else
{
getBollardInput(lastName,firstName,
poolDepth,poolDiameter,
deckLength,deckWidth);
}
}
public static void getBollardInput(String lastName, String firstName,
double poolDepth, double poolDiameter,
double deckLength, double deckWidth)
{
//Bollard attributes
double bollardHeight=Double.parseDouble(
JOptionPane.showInputDialog(null,
"Enter bollard height in inches.","Bollard Height",
JOptionPane.PLAIN_MESSAGE));
double bollardDiameter=Double.parseDouble(
JOptionPane.showInputDialog(null,
"Enter bollard diameter in incehs.","Bollard Diameter",
JOptionPane.PLAIN_MESSAGE));
int numberOfBollards=Integer.parseInt(
JOptionPane.showInputDialog(null,
"Enter the number of bollards.","Number of bollards",
JOptionPane.PLAIN_MESSAGE));
//Bollard instantiation
Bollards bollards= new Bollards(lastName,firstName,
poolDepth,poolDiameter,
deckLength,deckWidth,
bollardHeight, bollardDiameter,
numberOfBollards);
}
private static void displayOrders(BackYard[] orders, int numberOfOrders)
{
DecimalFormat dec3 = new DecimalFormat("0.000");
String divider = "******************************************************" +
"***********\n";
JTextArea textOut = new JTextArea(divider, 10, 30);
JScrollPane scroller = new JScrollPane(textOut);
for(int sub = 0; sub < numberOfOrders; sub++)
{
textOut.append("Customer Name: " + orders[sub].getLastName() + ", ");
textOut.append(orders[sub].getFirstName() + "\n");
textOut.append("Pool Depth:" +
dec3.format(orders[sub].getInsideDepth()) + "\n");
textOut.append("Pool Diameter: "+
dec3.format(orders[sub].getInsideDiameter()) + "\n");
textOut.append("Deck Width: " +
dec3.format(orders[sub].getDeckWidth()) + "\n");
textOut.append("Deck Length: " +
dec3.format(orders[sub].getDeckLength()) + "\n");
textOut.append("Number of Bollards Ordered: " +
orders[sub].getNumberOfBollards() + "\n");
textOut.append("Height of Bollards: " +
dec3.format(orders[sub].getBollardHeight()) + "\n");
textOut.append("Diameter of Bollards: " +
dec3.format(orders[sub].getBollardDiameter()) + "\n");
textOut.append("Cubic Yards of Concrete Needed: " +
dec3.format(orders[sub].getConcreteVolume()) + "\n");
textOut.append(divider);
} // end for loop
JOptionPane.showMessageDialog(null, scroller, "Orders Placed",
JOptionPane.PLAIN_MESSAGE);
} // end method DisplayOrders*/
}
Here is the BackYard interface:
public interface BackYard
{
//Universal constants
public static final int CU_IN_TO_CU_YD = 46656;
public static final int FT_TO_IN = 12;
public static final double DENSITY = 3.75; // in inches
//Pool constants.
public static final String DEFAULT_NAME = "Unknown";
public static final int DEFAULT_DIAM_DEPTH = 0;
public static final int STANDARD_DEPTH = 24; // in inches
public static final int STANDARD_DIAMETER = 6; // in feet
public static final int MIN_DEPTH = 10; // in inches
public static final int MAX_DEPTH = 72; // in inches
public static final int MIN_DIAMETER = 3; // in feet
public static final int MAX_DIAMETER = 25; // in feet
//Deck constants
public final static double MAX_DECK_LENGTH = 50.0; // in feet
public static final double MAX_DECK_WIDTH = 50.0; // in feet
public static final int DEFAULT_WIDTH_AND_LENGTH = 0;
//Bollard constants
public static final double MAX_BOLLARD_HEIGHT = 60.0; // in inches
public static final double MIN_BOLLARD_HEIGHT = 24.0; // in inches
public static final double MAX_BOLLARD_DIAMETER = 18.0; // in inches
public static final double MIN_BOLLARD_DIAMETER = 3.0; // in inches
public static final int MIN_NUMBER_OF_BOLLARDS = 4; // units
//Methods.
public abstract String getLastName();
public abstract String getFirstName();
public abstract double getInsideDepth();
public abstract double getInsideDiameter();
public abstract double getDeckWidth();
public abstract double getDeckLength();
public abstract int getNumberOfBollards();
public abstract double getBollardHeight();
public abstract double getBollardDiameter();
public abstract double getConcreteVolume();
}
Here is the pool class
public class Pool implements BackYard
{
// instance variable(s)
private double insideDiameter; // in feet
private double insideDepth; // in inches
private String lastName;
private String firstName;
// class variable(s)
public static int numberOfOrders;
// Zero argument constructor. Sets instance variables to default values
public Pool()
{
setInsideDiameter(DEFAULT_DIAM_DEPTH);
setInsideDepth(DEFAULT_DIAM_DEPTH);
setLastName(DEFAULT_NAME);
setFirstName(DEFAULT_NAME);
}
// Two parameter constructor.
// Sets names to input values and measurements to standard values
public Pool(String lastNameIn, String firstNameIn)
{
setInsideDiameter(STANDARD_DIAMETER);
setInsideDepth(STANDARD_DEPTH);
setLastName(lastNameIn);
setFirstName(firstNameIn);
numberOfOrders++;
}
// Three parameter constructor.
// Sets names and depth to input values and diameter to standard value
public Pool(String lastNameIn, String firstNameIn, double depthIn)
{
setInsideDiameter(STANDARD_DIAMETER);
setInsideDepth(depthIn);
setLastName(lastNameIn);
setFirstName(firstNameIn);
numberOfOrders++;
}
// Three parameter constructor.
// Sets all instance variables to input values
public Pool(String lastNameIn, String firstNameIn, double depthIn,
double diameterIn)
{
setInsideDiameter(diameterIn);
setInsideDepth(depthIn);
setLastName(lastNameIn);
setFirstName(firstNameIn);
numberOfOrders++;
}
// returns depth
public double getInsideDepth()
{
return insideDepth;
}
// validates input and sets depth
public void setInsideDepth(double inDepth)
{
insideDepth = ((inDepth >= MIN_DEPTH &&
inDepth <= MAX_DEPTH) ? inDepth : DEFAULT_DIAM_DEPTH);
}
// returns diameter
public double getInsideDiameter()
{
return insideDiameter;
}
// validates diameter and sets diameter
public void setInsideDiameter(double inDiameter)
{
insideDiameter = ((inDiameter >= MIN_DIAMETER &&
inDiameter <= MAX_DIAMETER) ? inDiameter : DEFAULT_DIAM_DEPTH);
}
// validates and sets last name
public void setLastName(String lastNameIn)
{
lastName = ((lastNameIn.length()) > 0 ? lastNameIn : DEFAULT_NAME);
}
// returns last name
public String getLastName()
{
return lastName;
}
// validates and sets first name
public void setFirstName(String firstNameIn)
{
firstName = ((firstNameIn.length()) > 0 ? firstNameIn : DEFAULT_NAME);
}
// returns first name
public String getFirstName()
{
return firstName;
}
// calculates total concrete necessary in cubic yards and returns that value
#Override
public double getConcreteVolume()
{
if(getInsideDiameter() == 0 || getInsideDepth() == 0)
return 0.000;
else
return (getCylinderVolume(getInsideDiameter() * FT_TO_IN + DENSITY +
DENSITY, getInsideDepth() + DENSITY) / CU_IN_TO_CU_YD) -
(getCylinderVolume(getInsideDiameter() * FT_TO_IN,
getInsideDepth())) / CU_IN_TO_CU_YD;
}
// private utility method used to calculate the volume of a cylinder
public double getCylinderVolume(double diameter, double height)
{
return (Math.PI * Math.pow(diameter / 2.0, 2)) * height;
}
} //end class Pool
Ever signed a contract before?
This code:
public class Pool implements BackYard
is just like one. It's like Pool saying to Backyard: "Hey Backyard, I'm signing a contract that guarantees I'll create code for all the methods you have."
But Pool violated the contract.
The police (compiler) finds out about it and says: Do it buddy or make your kids do it.
Either you fullfil the contract yourself (i.e. create code for all methods mentioned in Backyard) or let your descendants be the ones to complete it (the subclasses will be the ones to add code). You're kind of "punished" - keeping you in an abstract state until the commitment is completed.
First concrete class must implement all abstract methods from its supertypes. In your case you either make Pool abstract, all implement all abstract methods from supertypes that are not already implemented.
In other words, If you allowed not abstract class Pool to have abstract methods, then client of your library could do
Pool p = new Pool();
p.getBollardHeight();
which cannot work, because this method is not implemented. If, on the other hand, you made Pool abstract, you would not be allowed to instantiate it and the problem above would not occur.
You must create all the methods you see in BackYard, inside the Pool class
I have a list of values (Weather data), the people who wrote the list used the value "9999" when they did not have a value to report. I imported the text file and used the following code to take the data, and edit it:
import java.io.*;
import java.util.*;
public class weatherData {
public static void main(String[] args)
throws FileNotFoundException{
Scanner input = new Scanner(new File("PortlandWeather2011.txt"));
processData(input);
}
public static void processData (Scanner stats){
String head = stats.nextLine();
String head2 = stats.nextLine();
System.out.println(head);
System.out.println(head2);
while(stats.hasNextLine()){
String dataLine = stats.nextLine();
Scanner dataScan = new Scanner(dataLine);
String station = null;
String date = null;
double prcp = 0;
double snow = 0;
double snwd = 0;
double tmax = 0;
double tmin = 0;
while(dataScan.hasNext()){
station = dataScan.next();
date = dataScan.next();
prcp = dataScan.nextInt();
snow = dataScan.nextInt();
snwd = dataScan.nextInt();
tmax = dataScan.nextInt();
tmin = dataScan.nextInt();
System.out.printf("%17s %10s %8.1f %8.1f %8.1f %8.1f %8.1f \n", station, date(date), prcp(prcp), inch(snow), inch(snwd), temp(tmax), temp(tmin));
}
}
}
public static String date(String theDate){
String dateData = theDate;
String a = dateData.substring(4,6);
String b = dateData.substring(6,8);
String c = dateData.substring(0,4);
String finalDate = a + "/" + b + "/" + c;
return finalDate;
}
public static double prcp(double thePrcp){
double a = (thePrcp * 0.1) / 25.4;
return a;
}
public static double inch(double theInch){
double a = theInch / 25.4;
if(theInch == 9999){
a = 9999;
}
return a;
}
public static double temp(double theTemp){
double a = ((0.10 * theTemp) * 9/5 + 32);
return a;
}
}
The problem I am having is taking the values and checking for all times "9999" comes up, and printing out "----". I don't know how to take in a value of type double, and print out a String.
This code takes the values and checks for the value 9999, and does nothing with it. This is where my problem is:
public static double inch(double theInch){
double a = theInch / 25.4;
if(theInch == 9999){
a = "----";
}
return a;
}
I'm sorry if I put to much information into this question. If you need me to clarify just ask. Thanks for any help!
You need to modify your inch function to return a string, not a double.
public static String inch(double theInch){
if(theInch == 9999){
return "----";
}
return Double.toString(theInch/25.4);
}
I think the first problem might be that you're reading all the values from the Scanner as int instead of doubles. For example, based on your System.out.println() statement, I think you should actually be reading the following data types...
prcp = dataScan.nextDouble();
snow = dataScan.nextDouble();
snwd = dataScan.nextDouble();
tmax = dataScan.nextDouble();
tmin = dataScan.nextDouble();
Also, seeing as though the inch() method is only going to be used in the System.out.println() line, you'll need to change it to a String as the return type...
public String inch(double theInch){
if (theInch == 9999){
return "----";
}
return ""+(theInch/25.4);
}
should be an easy one. I originally was gonna do this in javascript but have to do it prior to setting to the form in my handler page. Anyway I need to make these values have 2 decimal places. Ex 219333.5888888 needs to be 219333.58. Is there a trim function or something?
form.setUnitRepairCost(Double.toString(jobPlanBean.getUnitTotalCost())); //UNIT REPAIR COST
form.setUnitMaterialCost(Double.toString(jobPlanBean.getUnitTotalMaterialCost())); //UNIT MATERIAL COST
here is the simple example to format the decimal value
import java.text.*;
public class DecimalPlaces {
public static void main(String[] args) {
double d = 1.234567;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d));
}
}
multiply the double by 100.0 and cast this to an int then take that int and cast it to a double and divide by 100.0
int temp = (int)(longDouble*100.0);
double shortDouble = ((double)temp)/100.0;
public static void main(String[] args) {
double d = 6.3546;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d));
}
For getting a double back and not a string:
double d = 80.123;
DecimalFormat df = new DecimalFormat("#.##");
double p = Double.parseDouble(df.format(d));
How about:
new java.text.DecimalFormat("0.00").format( yourNumber );
Here is String manipulation to truncate double value up to tow decimal places.
public static String truncateUptoTwoDecimal(double doubleValue) {
String value = String.valueOf(doubleValue);
if (value != null) {
String result = value;
int decimalIndex = result.indexOf(".");
if (decimalIndex != -1) {
String decimalString = result.substring(decimalIndex + 1);
if (decimalString.length() > 2) {
result = value.substring(0, decimalIndex + 3);
} else if (decimalString.length() == 1) {
result = String.format(Locale.ENGLISH, "%.2f",
Double.parseDouble(value));
}
}
return result;
}
return null;
}
As suggested by other you can use class DecimalFormat of java.text.DecimalFormat. We can also use DecimalFormat to round off decimal values.
Example:
import java.math.RoundingMode;
import java.text.DecimalFormat;
public class DecimalDemo {
private static DecimalFormat decimalFormatter = new DecimalFormat("#.##");
public static void main(String[] args) {
double number = 2.14159265359;
System.out.println("Original Number : " + number);
System.out.println("Upto 2 decimal : " + decimalFormatter.format(number)); //2.14
// DecimalFormat, default is RoundingMode.HALF_EVEN
decimalFormatter.setRoundingMode(RoundingMode.DOWN);
System.out.println("Down : " + decimalFormatter.format(number)); //2.14
decimalFormatter.setRoundingMode(RoundingMode.UP);
System.out.println("Up : " + decimalFormatter.format(number)); //2.15
}
}
Look into using a Decimal Format :
DecimalFormat twoDForm = new DecimalFormat("#.##");
By using those two methods you can handle all the exceptions also :
private String convertedBalance(String balance){
String convertedBalance = balance.toString();
Double d;
try {`enter code here`
d = Double.parseDouble(balance.toString());
Log.i("ConvertedNumber", "d (amount) = "+d.toString());
d = round(d, 2);
DecimalFormat f = new DecimalFormat("0.00");
convertedBalance = f.format(d);
Log.i("ConvertedNumber", "convertedBalance = "+convertedBalance);
}catch (NumberFormatException e){
Log.i("ConvertedNumber", "Number format exception");
}
return convertedBalance;
}
public static double round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}
Yes, DecimalFormat: http://www.exampledepot.com/egs/java.text/FormatNum.html
DecimalFormat Class
public static double truncateDecimals(double d, int len) {
long p = pow(10, len);
long l = (long)(d * p);
return (double)l / (double)p;
}
public static long pow(long a, int b) {
long result = 1;
for (int i = 1; i <= b; i++) {
result *= a;
}
return result;
}
You can simply use String.format() as below.
double height = 175.8653;
System.out.println("Height is: " + String.format("%.2f", height));
This will trim the double value to two decimal places.