Formatting Doubles To Two Decimal Places Within Return Statement

Jan 25, 2015

I'm attempting to format my doubles to two decimal places within my return statement. I have tried to use DecimalFormat but it gives me an error because my method needs to return a double and that results in a string being returned. I have also tried using the *100.00/100.00 method and that doesn't work when the number already ends in 0.

If I pass -150.00 it gives me -150.0 when I need two decimal places.

How can I go about doing this?

View Replies


ADVERTISEMENT

Formatting Answers To 2 Decimal Places

Sep 8, 2014

I've been scanning forums for answers to this problem, but most deal with simple programming that you might find in a classroom (i.e. "System.out.printf") which will not work in the GUI I'm attempting to complete. Here's the tale of the tape:

The GUI is a price calculator I'm developing for my company that takes input from drop-down menus and several Jtextfields and calculates the answer based on the values contained within each. It's completely done (and functional), so I'd rather not change too much if at all possible. Because I'm dealing with decimal values then I'm getting 9 decimal places in the output JLabel, though. In order to display the answer, I'm using a series of "totalPrice.setText(..." declarations.

Because there is a fair amount of text and the values in the calculation are constantly changing, is there a way to 'simply' format the output JLabel to display only 2 decimals? Or is there an alternative solution that would work--say with a JTextfield instead--without having to completely re-code the calculator?

View Replies View Related

Formatting User Answer To Two Decimal Places

Nov 20, 2014

I am writing a simple learning program that does basic math. Everything is working as needed except for when it comes to division. I need to know if there is a way to format the users input to two decimal places and that when the program checks the users answer against the division, it gives it a yay or nay. Right now, it wants the answer out to 12 decimal places.

So for 5/3

I would like it to accept the answer 1.67

not 1.666666666667

Is there a way to do this?

View Replies View Related

Convert Java Code To Display Using Printf Statement With Two Decimal Places To Right

Feb 26, 2015

How i would convert this java code to display using the printf statement, with two decimal places to the right...here is the source code so far, but it has a few errors and needs to be reformated for printf

import java.util.Scanner; // scanner class
public class PROB3_CHAL15
{
public static void main(String[] args)
{
double checks =0,
totalfee =0,
fee = 10,
fee1 =.1,
fee2 = .08,
fee3 = .06,
fee4 = .04,
checkFee;
String input;
Scanner keyboard = new Scanner(System.in);
 
[code]...

View Replies View Related

How To Add Decimal Format Up To Two Places

Jul 25, 2014

import javax.swing.JOptionPane;
import java.text.DecimalFormat;
public class Sample3 {
public static void main(String args[]){
double amount,iRate,monPay,totalPay;
int years;
String amountStr;

[Code] ....

View Replies View Related

Printing 2 Decimal Places - Printf Not Working?

Mar 22, 2014

I need to print to 2 decimal places and I'm trying to use the printf method, but for some reason I keep getting an error. I've looked through my code, but unless I'm missing a small detail, it looks okay to me.

float sum = 0;
float avg = 0;
double[] rain = {0, 1.9, 1.5, 1.2, 1.1, 0.5, 0.03, 1.0};
 
//Calculate sum of rain.
for (int i = 1; i <= 7; i++) {
sum += rain[i];
 
[Code] ....

View Replies View Related

How To Format Methods To Display Number With 1-2 Decimal Places

May 8, 2014

I am working with a program I wrote for class. I got it to compile and do what I want, But I was wondering how I can format my methods to to display a decimal with 1-2 decimal places. Would I create a method in my NumberAnalysis class to do it for me? Or would I declare an instance of the DecimalFormat class in my main method?

import java.util.Scanner; //Needed for Scanner Class
import java.io.*; //Need for File and IOException
import java.text.DecimalFormat;
public class Ex8_11 { 
public static void main(String[] args) throws IOException{
{
DecimalFormat decformatter = new DecimalFormat("#0.00");
 
[Code] .....

This is my output:

Lowest Number: 1.09
Highest Number: 82.76
Total Number: 367.89000000000004
Total Average Number: 30.657500000000002

Think I just solved the answer to my own question, I did it by declaring double variables in my main method and called the methods and instantiated the variables into the methods... Is there a better way to do this?

package lesson4.skowronek;
 import java.util.Scanner; //Needed for Scanner Class
import java.io.*; //Need for File and IOException
import java.text.DecimalFormat;
public class Ex8_11 {
public static void main(String[] args) throws IOException{
 
[Code] ....

View Replies View Related

Floating Point Precision - Output With Two Decimal Places?

Jan 27, 2015

Consider this small program and output.

public class Floating{
public static void main( String[] args ){
System.out.println( 2.80 - 1.75 );
}
}

The output is 1.0499999999999998. Why not 1.05?

View Replies View Related

Include Three Sides Of Triangle Formatted To Two Decimal Places

Sep 9, 2014

My program is supposed to include The three sides of the triangle formatted to two decimal places The perimeter formatted to one decimal place The area formatted to one decimal place The unformatted area. It does run, but it is not decimal formatted. I have read my book to try and figure out how to do this, but it doesn't make since to me.

import javax.swing.JOptionPane;
import java.util.*;
import java.text.DecimalFormat;
import java.util.StringTokenizer;
 
public class ShelbyHarms_3_03 {
public static void main (String [] args) {
double a, b, c; //Input sides of triangle

[Code] ....

View Replies View Related

Type Casting - Getting Number With Two Decimal Places As Output?

Jun 7, 2013

"Type Casting" .... So the question is "How am I getting a number with two decimal places as output?"

import java.util.Scanner;
public class SalesTax
{
public static void main(String[] args) {
double purchase, tax;
Scanner input = new Scanner(System.in);
System.out.print("Enter purchase amount: ");
purchase = input.nextDouble();
tax = purchase * 0.06;
System.out.println("Sales Tax: $" + (int)(tax * 100) / 100.0); +//this will give two decimal places??+
}
}

View Replies View Related

Arithmetic Expression That Will Display Doubles To Only One Decimal Place?

Sep 29, 2014

I am looking to find a way to display the number of decimal places without using any type of formatting string.

Only to make it xxx.x instead of xxx.xxxxxx.

View Replies View Related

Inserting Else Statement And Multiple Brackets At Various Places

Jan 16, 2014

I'm using this try statement to check for errors in input in my Tic Tac Toe game. The problem I have having is I don't understand why this error is happening. It's preventing my code from compiling. I've tried inserting an else statement and multiple brackets at various places with no success.

Java Code:
public void play(){
Scanner input = new Scanner(System.in);
int row, col;
char currPlayer = 'X';

[code]....

View Replies View Related

Return Smallest Of 10 Doubles (User Input)

Oct 1, 2014

This code will let a user type 10 double's, and return the smallest of those 10 double's. But I don't really understand what happens in de last for-loop.

package hsleiden.webcat.exercise06_09;
import java.util.Scanner;
public class Exercise06_09
{
public static void main (String[] args){
double[] allNumbers = new double [10];
 
[Code] ....

View Replies View Related

Area And Perimeter Of Triangle - Decimal Formatting Error?

Sep 28, 2014

I am also having trouble with another program.

Java Code:

import javax.swing.JOptionPane;
import java.util.*;
import java.text.DecimalFormat;
import java.util.StringTokenizer;
public class ShelbyHarms_3_03 {
public static void main (String [] args) {
double a, b, c; //Input sides of triangle
double x; //Perimeter of triangle
double area; //Area of triangle

[Code] .....

Here are the errors:

ShelbyHarms_3_03.java:39: error: variable x might not have been initialized
JOptionPane.showMessageDialog(null, formatter.format(x));
^
ShelbyHarms_3_03.java:42: error: variable area might not have been initialized
JOptionPane.showMessageDialog(null, formatter.format(area));
^
2 errors

Am I not formatting the decimal format right?

View Replies View Related

Java Program - Distance Traveled (Formatting And Decimal Place)

Apr 10, 2014

I'm having trouble formatting my output and issues with the decimal places. Here's my code:

import java.util.Scanner;
import java.text.DecimalFormat; // Imports DecimalFormat class for one way to round
 public class lab3 {
public static void main(String[] args) {
String heading1 = "Hour", heading2 = "Distance Traveled";
int timeElapsed, hour, speed;

[Code] ....

And here's my output (Click on the image since it's pretty small):

javaIssues.png

Issue:
1) The Hours 2 and 3 aren't aligned to 1.
2) The 80 and 120 in Distance Traveled have 6 decimal places when it should not have decimals.

View Replies View Related

Return Statement In A Constructor

Jan 8, 2014

What is the difference between two statements:

Class1 class1 = new Class();
class1 = Class2.method1();

and

Class1 class1 = Class2.method1();

I have one more query on the same lines ... I always need to call the method1 of Class2 whenever i create a object of class1. So I wanted to go with the constructor in Class1. But the method1 in Class2 has a return statement. so is there any better way to do this other than constructors.

Sample code:

public int class Class2{
public static method1(){
return 2;
}
}
public class Class1{
public Class1(){
Class2.method1();
}
}

View Replies View Related

Missing Return Statement

Nov 20, 2014

This was an example of code that I'm trying to get to work, I swear I took it down just as it was written in class however mine says missing return statement....

Scanner keyb = new Scanner(System.in);
System.out.print("enter rows and columns");
int rows = keyb.nextInt();
int cols = keyb.nextInt();
int[] [] array = new int [rows] [cols];
printArray(array);

[code]....

View Replies View Related

Method Return Statement

Apr 2, 2014

Im having trouble with my method return. I am new to using methods and cant seem to grasp the idea on the return part. I have to write a method that tells if a number is prime or not. This is what I have so far and it wont compile because it is saying "missing return statement } "..

import javax.swing.JOptionPane;
public class IsPrimeMethod
{
public static void main(String []args)
{
String primeNum;
int number;
int i = 2;
 
[code]....

View Replies View Related

Return Statement In Method Overriding

Jan 1, 2015

class Base
{
public Base rtc() {
System.out.println("am in parent");
return new Base();
}
}
class Ret extends Base

[Code] ....

Output :

I am in child class but b1.rtc requires b2 to hold the return value y not Ret's object.

View Replies View Related

Passing Parameters And Return Statement

Apr 27, 2014

My task is to make a mortgage calculator where the user selects which calculation they want the program to do via a menu. I got the menu to work and it keeps on looping until terminated so that's good. The starts when I want the user's choice (P, I or T) to be used in another method which will then execute another set of code (the calculation that needs to be done). I think passing parameters and return statements are what I need to use, but after reading and watching videos, I'm still not sure how to implement it into my program. For now, I want the user to input the letter "P" and then I want that information to be passed to the method, loanCalculator() where the if statement will make a decision to call the method, calcPayment and display the number 0 via the console. Once it can do that, I'll fill in the calculation methods with the proper code since I can at least navigate the user input to its associated calculator. It just keeps on looping the menu without going through the other methods.

import java.util.Scanner;
//Example of "big loop" in main to repeat using a No Trip (0,N) test first
public class Mortgage {
// constants
static double loanAmount;
static double interestRate;
static int term;

[code]....

View Replies View Related

How Does Return Statement Work In Try Catch Block

Jul 2, 2014

consider this program :

public class hello {
/**
* @param args
*/
public static void main(String[] args) {
int s = new hello().h();
System.out.println(s);
} public int h(){
try{
int g = 10/0;

[Code] .....

the output is 7. how the flow is working. i understand that there is a divide by zero exception after which the control goes to catch. what about the return statement in catch . why is it overridden by finally..........

View Replies View Related

Argument Program - Missing Return Statement

Jan 22, 2015

I am trying to compile the arguments program but it is giving missing return statement error. how to correct the error message.

public class Arguments {
public static Void main ( String args[])
{
int count, i=0;
String sdata;

[code]...

View Replies View Related

Incrementing Array Index During Return Statement

Feb 14, 2015

I am trying to understand the following code.This return statement should actually return the char at myArray[index] first, then increments the index afterwords correct?

Public char next(){
return myArray[index++];
}

View Replies View Related

If Statement Requires A Return Of Type Boolean

Dec 6, 2014

Im trying to do this

if( 2/2 ) {
system.out.println( "number is not event" );
} else {
system.out.println( "number is event" );
}

However if statement requires a return of type boolean. So im forced to this instead

if( (2/2) != 0 ) {
system.out.println( "number is not event" );
} else {
system.out.println( "number is event" );
}

Is there a way to achieve the former method, without typecasting, if you had to typecast how do you do it?

View Replies View Related

JDBC SQLException - Statement Did Not Return Result Set

May 4, 2014

I get an Sqlexecption with this message "com.microsoft.sqlserver.jdbc.SQLServerException: The statement did not return a result set."

When I execute this query :

...
Statement stmt = conn.createStatement();
stmt.executeUpdate("IF EXISTS (SELECT name FROM master.sys.databases WHERE name = N'Repository')
"
                + "PRINT 'Database exists'

[Code] .....
 
I want to create a database and a table in sql server if it doesn't exist. How can i prevent this error.

View Replies View Related

User Input Random Numbers Then Program Sort Them In Different Ways - Missing Return Statement

Apr 7, 2014

I have been assigned to write a program that has a user input random numbers then the program is to sort them in different ways. I have the coding for the different sorts but, I have an error saying that I am missing a return statement in the "Bubble" method. I am trying to return "arr[i]" in the "for loop" which gives me this error, and when I try to take the "return arr[i]" outside of the "for()" loop the error reads the it cannot locate variable "i".

import java.awt.* ;
import java.awt.event.*;
import javax.swing.*;
public class SwingSorts extends JFrame implements ActionListener
{
JRadioButton bubble;
JRadioButton selection;

[Code] .....

View Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved