Converting double to strings
I'm having a problem in getting my double to convert to a string, here's my code so far.
public void calculatePayments()
double paymentAmount;
double monthlyInterestRate = (Double.parseDouble(interestBox.getText())/12)/100;
double amountOfLoan = Double.parseDouble(balanceBox.getText());
double numberOfPayments = Double.parseDouble(yearsBox.getText()) * 12;
paymentAmount = (amountOfLoan * monthlyInterestRate) / (1 - Math.pow(1/(1 + monthlyInterestRate),numberOfPayments));
Double.toString(paymentAmount);
tableBox.append(paymentAmount);
And here's the error message I get:
ProgramInterface.java:134: append(java.lang.String) in javax.swing.JTextArea cannot be applied to (double)
tableBox.append(paymentAmount);
As always, help is appreciated.
This line returns a String but has no affect on paymentAmount.
Double.toString(paymentAmount);To covert the double to String you can save the return in a variable
String s = Double.toString(paymentAmount);
tableBox.append(s);or combine them
tableBox.append(Double.toString(paymentAmount));
Similar Messages
-
I am looking for a way to convert double to String.
I think that I have to use wrapper like Double class and use toString(double d), but I am not sure how to do it.
Since toString() is static method, I do not have to have an instance of the Double class, so I was wondering what's the correct way to do it.
I need something like this:
String MyString = new String (String1.concat ( My_doubleNumber.Double.toString() ) );
Any Suggestions?
Thanks!!!WOW thanks a lot. These are definately better than what I thought of doing originally.
In case I need to use the wrapper class somewhere else, I am just wondering what would be a proper use of Double and String? -
Converting Double to String without exponent
Hi all,
I am reading some values from Excelsheet using apache POI library. I have large numbers that need to stored into database as string and not numbers. hence, while reading the excelsheet values, i convert these number.. and the are received as double. While converting double into string I noticed that some values are represented in exponential form.. I would like to avoid this and have pure number values in the form of string,,..
Can anybody tell me how to do it?
Thanks in advance,
Abdel Olakarajava.text.DecimalFormat
-
Newbie Converting double to string
I am very new to Java Programming, but I am trying to convert a double to a string
Here is some code of what I am trying to do:
String output = "";
Word words[] = new Word[ 7 ];
Then I add the "words" to the array
for ( int i = 0; i < words.length; i++ ) {
output += words[ i ].toString();
output +="\nListed :" + Double.toString(words[ i ].listings()) + "\n";
return output; the listings method is type double. I think I can use toString to convert a double to a string but am not sure how to go about doing it.
Any help is very appreciated.
Thanks.I am very new to Java Programming, but I am trying to
convert a double to a string
Here is some code of what I am trying to do:
String output = "";
Word words[] = new Word[ 7 ];
Then I add the "words" to the array
for ( int i = 0; i < words.length; i++ ) {
output += words[ i ].toString();
output +="\nListed :" + Double.toString(words[ i
].listings()) + "\n";
return output;the listings method is type double. I think I can use
toString to convert a double to a string but am not
sure how to go about doing it.
Any help is very appreciated.
Thanks.Wrong:
Double.toString(words[ i ].listings())
Right:
words[ i ].listings().toString() -
Convert Double to String and Specify Precision
Hi.....
Can anyone tell me what class/method I would use if I want to convert a double to a string and need the ability to specify the precision?
Thanks,
ChristineDecimalFormat
-
Trouble converting "double like" string to integer
Hi everyone,
I have a trouble here. Let's say I have a string which its value is "314.12345667". the value is "like a double". How do i convert it into an integer where the integer only takes the value of da string before the decimal point (as in the value of string = 314 only)? Thanks for helping.hi xamule,
tey this..
String s="314.123876"
double d=Double.parseDouble(s);
int x=d.intValue();
hope it may help u..
bye bye,
Pramod -
I'm sorry if this has already been posted, but i searched the database for a while and i couldn't find anything that helped. I was just wondering what the code was to convert a double into a string, so it can be displayed on a label or button, etc. Again, i am sorry if this was already posted and i missed it.
double d=100.0;
String doubleStr=Double.toString(d); -
Convert Double to String without zeros at the end
Hello,
how can i convert a double-numeric to a string? I know how can do it but not how i can do it in a fast way.
When i use the "Number to Fractional String"-Object then a number
1,2 --> is canged to 1,200000
1,0 --> changed to 1,000000
what can i do that there are no zeros at the end?
Currently i´m reading the reversed string in a loop to remove the zeros, but this i to slow i think.
Is there a fast way?
Thanks for your helpExtract from the LV help :
Select Tools»Options to display the Options dialog box and select
Front Panel from the Category list to display
this page.
Use this page to set front panel options.
This page includes the following components:
Open the control editor with double click—Allows you to
double-click a control to display the Control
Editor window. Use the Control Editor window to customize
the appearance of a front panel object. This checkbox is unchecked by default.
Use localized decimal point—Uses the decimal separator for
the operating system instead of the period. This checkbox is checked by default.
Remove the checkmark from this checkbox if you want LabVIEW to use periods in
all cases for the decimal point. -
Hello,
I have the following method:
private String doubleToString(double value, int kommas)
int stringLength;
String mString ="";
String mSubstringSuf ="";
Double dValue = new Double(value);
mString = new String(dValue.toString());
stringLength = mString.length();
mSubstringSuf = mString.substring(2, stringLength + 2 - kommas);
return "0." + mSubstringSuf;
Now I call this Method with
value = 4.98
kommas = 2
I receive back the value 4.88????
What is wrong?
Thank you
WernerThat code cannot possibly return "4.88". It always returns something that begins with "0." So perhaps you are debugging the wrong code.
-
Re: convert double to string?
outputLabel.setText(String.valueOf(bmi));
Thank you all very much,
theoutputLabel.setText(String.valueOf(bmi));[/co
de] took care of the compiling, but the program
crashes when the calculate button is clicked and
returns a NULL POINTER EXCEPTION. This is my first
experience with this error. What does it mean?
Thanx,
RipIt means you tried to call a method or access a field on a null reference?
Which line does it occur in? (The error message will tell you, and will alos tell you where the method was called from.)
For instance, if the message comes from the outputLabel.setText line, then outputLabel must be null, since that's the only reference you're attempting to dereference there.
If it comes from a different line, look for everything other than class names preceding a dot, or for references to array elements (e.g. arr[0] will give NPE if arr is null). -
Is there an easy way to convert from a String with a comma, ie. 1,000.00 to a float or a double?
thanks,
dosteovLike DrClap said: DecimalFormat. However, make sure you understand the Locale things, as explained at http://java.sun.com/j2se/1.3/docs/api/java/text/DecimalFormat.html (which refers to NumberFormat as well) and use them explicitly. Like
public class FormatTest
public static void main(String args[])
try
// see NumberFormat.getInstance()
DecimalFormat fmt = new DecimalFormat();
Number num = fmt.parse("1,000.01");
System.out.println(num.doubleValue());
catch(ParseException pe)
System.out.println(pe);
}most likely seems OK on your system, but may print "1.0" (or even fail) on some non-English platforms!
When performing calculations, also see http://developer.java.sun.com/developer/JDCTechTips/2001/tt0807.html
a. -
How can I Convert a numeric string to a formatted string?
I have a string value returned from a background tool that will range from 0 to possibly terabytes as a full number. I want to format that number to use commas and to reduce the character count using an appropriate size modifier (KiB, MiB, GiB, etc). I've tried converting the string number to a Double value using Double.parseDouble() and then performing the math based on the size of the value with this code:
Double dblConversionSize;
String stCinvertedSize;
dblConversionSize = Double.parseDouble(theValue);
if (dblConversionSize > (1024 * 1024 * 1024))
stConvertedSize = String.format("%,.000d", dblConversionSize / 1024 / 1024 / 1024) + " TiB";
I've also tried using
String.valueOf(dblConversionSize / 1024 / 1024 / 1024) + " TiB";
However, the formatting is failing and I'm either getting a format exception or the result is displayed as a number with no decimal component.
Anyone have a recipe for this?
Thanks,
TimTOLIS Tim wrote:
Thanks, but the reason for using Double is that the division math can leave me with values like 2.341 GiB. I don't want to drop the values (or round) on the right side of the decimal point.
Then you may look for DigDecimal which avoids digitization errors.
NumberFormat will handle all subclasses of Number. You might need another specialization. Just look at the API which one is suitable.
bye
TPD -
Converting objects into Strings
How would someone convert an object of say (String, int, double, String) into a readable string. I tried the toString() method but all I get is something like this
Student@1f12c4e..I'm not sure I understand "how" to override. The whole point of this project is to use quicksort on a list of students, unfortunately all I get is the address whenever I use the .toStrings() method.
Here's what I have, any help would be greatly appreciated-so very close
import cs1.Keyboard;
import java.io.*;
import java.util.*;
public class StudentTraverse
public static void main(String[] args)
String newName;
int newSocial;
double newGPAs;
String newMajors;
System.out.println("How many Students would you like to add");
Student newStudent;
StudentList12 WORK = new StudentList12();
int total = Keyboard.readInt();
for(int number = total; number > 0; number--)
System.out.println("Name?");
newName = Keyboard.readString();
System.out.println("Social?");
newSocial = Keyboard.readInt();
System.out.println("GPA?");
newGPAs = Keyboard.readDouble();
System.out.println("Major?");
newMajors = Keyboard.readString();
newStudent = new Student(newName, newSocial, newGPAs, newMajors);
System.out.println("Inserting: "+newStudent.toString());
WORK.add(newStudent);
for(total = 0; total < WORK.size(); total++)
System.out.println("top" total": "+WORK.top(total).toString());
try
BufferedReader in = new BufferedReader(new FileReader("LIST.out"));
while (in.ready())
// Print file line to scree
System.out.println (in.readLine());
in.close();
catch (Exception e)
System.err.println("File input error");
public class StudentNode
public Student student;
public StudentNode next;
public StudentNode()
next = null;
student = null;
public StudentNode(Student d, StudentNode n)
student = d;
next = n;
public void setNext(StudentNode n)
next = n;
public void setData(Student d)
data = d;
public StudentNode getNext()
return next;
public Student getData()
return data;
public String toString()
return ""+data;
public StudentNode(Student newStudent)
METHOD NAME: StudentNode
AUTHOR:
DATE OF CREATION: Nov 20, 2004
DATE OF UPDATES: Nov 28, 2004
PURPOSE: Acts as a node for the Student list
ALGORITHM:Acts as node for the list
INSTANCE VARIABLES: none
student = newStudent;
next = null;
public class Student
private String name;
private int social;
private double GPA;
private String Major;
public Student(String newName, int newSocial, double newGPAs, String newMajors)
METHOD NAME: Student
AUTHOR:
DATE OF CREATION: Nov 20, 2004
DATE OF UPDATES: Nov 28, 2004
PURPOSE: The actual Student class, determines what is allowed in the array
ALGORITHM:Declare what variables will be needed for the program
INSTANCE VARIABLES: String name, int social, double GPA, String Major
name = newName;
social = newSocial;
GPA = newGPAs;
Major = newMajors;
import java.io.*;
import cs1.Keyboard;
import java.io.BufferedWriter;
import java.util.*;
public class StudentList12
private StudentNode list;
static int i = 0;
public StudentList12()
METHOD NAME: StudentList12
AUTHOR:
DATE OF CREATION: Nov 20, 2004
DATE OF UPDATES: Nov 28, 2004
PURPOSE: Declares the Node
ALGORITHM:Declare the Node
INSTANCE VARIABLES: none
list = null;
public boolean isEmpty()
return list == null;
public int size()
return i;
public void add(Student newStudent)
METHOD NAME: add
AUTHOR:
DATE OF CREATION: Nov 20, 2004
DATE OF UPDATES: Nov 28, 2004
PURPOSE: Let's users add objects to the array of objects
ALGORITHM:Traverses the current list and adds object to the end
INSTANCE VARIABLES: none
list = new StudentNode(newStudent, list);
i++;
current = current.next;
current.next = node;
public Student remove()
if(isEmpty())
return null;
StudentNode tmp = list;
list = tmp.getNext();
i--;
return tmp.getData();
public void insertEnd(Student newStudent)
if(isEmpty())
add(newStudent);
else
StudentNode t = list;
while(t.getNext() != null)
t=t.getNext();
StudentNode tmp = new StudentNode(newStudent, t.getNext());
t.setNext(tmp);
i++;
public Student removeEnd()
if(isEmpty())
return null;
if(list.getNext() == null)
return remove();
StudentNode t = list;
while(t.getNext().getNext() != null)
t = t.getNext();
Student newStudent = t.getNext().getData();
t.setNext(t.getNext().getNext());
i--;
return newStudent;
public Student top(int n)
StudentNode t = list;
for(int i = 0; i <n && t != null; i++)
t = t.getNext();
return t.getData();
public void writeToFile(int n)
int z = n;
try
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("LIST.out")));
for(int counter = z; counter >= 0; counter--)
System.out.println(counter);
out.close();
catch(Exception e)
System.err.println("Couldn't Write File");
try
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("LIST.out")));
out.write(list.toString());
out.close();
catch(Exception e)
System.err.println("Couldn't Write File");
} -
Double.parseDouble(String) : Problem to parse large String
Hello,
I need to convert A String to a Double in my application without rounding of digits.
I have used the Double.parseDouble(String) method.
The maximum string length can be 17 including dot(.)
So if my String is (of length 17)
Eg.
S= �9999999999.999999� then I am getting the double value as
d= 9999999999.999998(compare the last digit)
If s = �9999999999.111111� then d = 9999999999.111110
If s = �9999999999.555555� then d = 9999999999.555555 (result that I want)
If s = �9999999999.666666� then d = 9999999999.666666 (result that I want)
If s = �9999999999.777777� then d = 9999999999.777777 (result that I want)
If s = �9999999999.888888� then d = 9999999999.888887
If s = �9999999999.999999� then d = 9999999999.999998
If s = �9123456789.123456� then d = 9123456789.123456
But string length up to 16 is giving me the accurate result
So any body can explain me that why it is happening? And how can i get the accurate result.
Thanks in advanced.Hi,
Thank You for your suggestion. By which i can store
the big double number in Data base , but at some
point i require to parse a double value from a Double
reference.In that case if the Decimal value length
=> 16 then it the last digit changes or rounds.
coverting 9999999999.999999 Decimal value to double
value. It gives me 9999999999.999998 and
9999999999.9999999 gives me the 10000000000.0000000.
but the Double value 999999999.999999 is ok
and 999999999.99999999 rounds.Err, is there a follow up question in there? -
How convert integer into string
Hi,
I need to convert answer3 from double into String
answer3 = Double.parseDouble(dij3)/(1 + Math.pow(( Double.parseDouble(tesside_luas_i) / Double.parseDouble(tesside_luas_j) ),0.5847));Now the integer value is string but why i cannot get valur from my servlet to my web page
package net.mybizaid.isodms.servlet;
import java.io.*;
import java.util.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import net.mybizaid.isodms.*;
public class SPLDataInputServlet extends HttpServlet {
public void doPost (HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
System.out.println( "******************** Calculation Servlet ******************" );
String dij ;
String population_i ;
String population_j ;
String project_name = "";
String project_status = "";
double answer;
String handler = "";
String url = "";
double answer3;
String dij3 ="";
String tesside_luas_i ="";
String tesside_luas_j ="";
double answer2;
String dij2 ="";
String luas_i ="";
String luas_j ="";
String counter = "";
String i = "";
handler = request.getParameter( "handler" );
dij = request.getParameter("dij");
population_i = request.getParameter("population_i");
population_j = request.getParameter( "population_j");
project_name = request.getParameter( "project_name");
project_status = request.getParameter( "project_status");
dij2 = request.getParameter("dij2");
luas_i = request.getParameter("luas_i");
luas_j = request.getParameter( "luas_j");
dij3 = request.getParameter("dij3");
tesside_luas_i = request.getParameter("tesside_luas_i");
tesside_luas_j = request.getParameter( "tesside_luas_j");
HttpSession session = null;
session = request.getSession(true);
int cnt = counter != null && !counter.equals("") ? Integer.parseInt(counter) : 0;
int ii = i != null && !i.equals("") ? Integer.parseInt(i) : 0;
//Tesside
if (handler != null && !handler.equals( "" ) && handler.equals( "cal3" ))
try
System.out.println("The DIJ3 value is :"+dij3);
System.out.println("The tesside_luas_i value is :"+tesside_luas_i);
System.out.println("The tesside_luas_j value is :"+tesside_luas_j);
answer3 = Double.parseDouble(dij3)/(1 + Math.pow(( Double.parseDouble(tesside_luas_i) / Double.parseDouble(tesside_luas_j) ),0.5847));
String str = String.valueOf( answer3 );
System.out.println("The answer value is :"+str);
url = "/jsp/model/tessideAnswer.jsp";
dispatchErrorMsg( request, response, url, "" );
catch (Exception e)
request.setAttribute("pd.errorMessage", e.getMessage());
dispatchErrorMsg( request, response, "/jsp/Error.jsp", e.getMessage() );
//PotensiPasaran
if (handler != null && !handler.equals( "" ) && handler.equals( "cal2" ))
try
System.out.println("The DIJ2 value is :"+dij2);
System.out.println("The luas_i value is :"+luas_i);
System.out.println("The luas_j value is :"+luas_j);
answer2 = Double.parseDouble(dij2)/(1 + Math.sqrt(( Double.parseDouble(luas_i) / Double.parseDouble(luas_j) )));
System.out.println("The answer value is :"+answer2);
url = "/jsp/model/potensiPasaranAnswer.jsp";
dispatchErrorMsg( request, response, url, "" );
catch (Exception e)
request.setAttribute("pd.errorMessage", e.getMessage());
dispatchErrorMsg( request, response, "/jsp/Error.jsp", e.getMessage() );
//Reilly
if (handler != null && !handler.equals( "" ) && handler.equals( "add" ))
try
System.out.println("The DIJ value is :"+dij);
System.out.println("The population_i value is :"+population_i);
System.out.println("The population_j value is :"+population_j);
answer = Double.parseDouble(dij)/(1 + Math.sqrt(( Double.parseDouble(population_i) / Double.parseDouble(population_j) )));
System.out.println("The answer value is :"+answer);
url = "/jsp/model/reillyAnswer.jsp";
dispatchErrorMsg( request, response, url, "" );
catch (Exception e)
request.setAttribute("pd.errorMessage", e.getMessage());
dispatchErrorMsg( request, response, "/jsp/Error.jsp", e.getMessage() );
public void doGet (HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
doPost(request, response);
}//end doGet
public void dispatchErrorMsg(HttpServletRequest req, HttpServletResponse res,
String target, String message)
try
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(target);
req.setAttribute("eshop.ErrMessage",message);
dispatcher.forward(req, res);
catch (Exception e)
System.err.println( e.getMessage() );
}//end class
Maybe you are looking for
-
GR/IR Clearing F.19 - No document generated
Hi I am trying to regouping the GR/IR account at period end but not getting any batch session while executing F.19. I have done following settings at OBYP:- Key BNG (Invoiced but not yet delivered) Reconcliliatin account as our GR/IR account Adjustme
-
Max capacity for sd card slot Mac Mini mid 2010
Has anyone with a MAC Mini mid 2010 tried using the SD card slot for an extended drive? I'm wondering what the max size is for the slot, and if I put a 64-128 gig SD Card in, would OS X 10.8.2 be able to combine that with an internal HD to create a
-
Best way to use CSS in random text
Mick White recommended this script for displaying random text. Is there a way to mod this so that it's can show multiple CSS styles (one style for the quote and one for the name)? Or should I do this another way? (I'm not great with databases yet.) T
-
Detecting the JVM version using Javascript in IE
Where can I find the neccessary code to detect the existance and version of the JRE/JVM installed on a client machine. I'm looking for something like this: http://java.sun.com/j2se/jre_check/index.jsp I'm not a Java programmer, I don't know how to co
-
Trouble uploading photos from iPad 2 to Blog?
Hi Everyone, After submitting this question to the forum...and reading many responses, I took matters into my own hands. (Apple was unable to offer a successful solution.) Apple has an ap: BLOGPRESS This works perfectly with Google's Blog...also kn