Java cast a string as a double [duplicate] - java

This question already has answers here:
Convert String to double in Java
(14 answers)
Closed 1 year ago.
Im creating a basic GUI that takes the amount entered by a user and subtracts it with a pre existing amount. However it will not let me to run the one below as I get an error of String cannot be converted to double. Using the parseInt method won't work here as im using the getText Method.
String message = txtaMessage.getText();
String transaction1 = txtfAmountTransfer.getText();
String reciever = txtfTransferTo.getText();
lblOutputTransferInfo.setText("Your Amount of "+transaction1+" has been sent to "+reciever+" .");
lblOutputTransferMsg.setText("With a Message: "+ message);
double balance = 5123.84;
String newBalance = balance - transaction1;//this will not work but the concept I need
lblSavingsBalance.setText(newBalance);

It won't work because here transcation1 is a string and whereas balance is double. In java, we don't have a method to subtract string from double. So, First, you need to convert transaction1 into double. I suggest you to
Double newBalance = balance - Double.parseDouble(transcation1);
then lblSavingsBalance.setText(newBalance.toString()); to convert newBalance double value to string
Hope it works fine...

If getText returns String below code will work.
String message = txtaMessage.getText();
String transaction1 = txtfAmountTransfer.getText();
String reciever = txtfTransferTo.getText();
lblOutputTransferInfo.setText("Your Amount of "+transaction1+" has been sent to "+reciever+" .");
lblOutputTransferMsg.setText("With a Message: "+ message);
double balance = 5123.84;
balance = balance - Double.parseDouble(transaction1);//this will not work but the concept I need
lblSavingsBalance.setText(String.valueOf(balance));
If you are using android,
(Assuming txtaMessage, transaction1, reciever are either TextView objects or EditText objects)
txtaMessage.getText(); //This won't return a String. This will return a CharSequence.
You have to convert it to string. So the correct method is,
String message = txtaMessage.getText().toString();
Do this for all EditTexts and TextViews.
Then transaction1 shoud be converted as Double
Double.parseDouble(transaction1);
After that you can substract transtraction1 from balance and assign it to the original balance.
balance = balance - Double.parseDouble(transaction1)
The full version of android code is below.
String message = txtaMessage.getText().toString();
String transaction1 = txtfAmountTransfer.getText().toString();
String reciever = txtfTransferTo.getText().toString();
lblOutputTransferInfo.setText("Your Amount of "+transaction1+" has been sent to "+reciever+" .");
lblOutputTransferMsg.setText("With a Message: "+ message);
double balance = 5123.84;
balance = (balance - Double.parseDouble(transaction1));//this will not work but the concept I need
lblSavingsBalance.setText(String.valueOf(balance));
If the transaction1 value is not a number, An Exception will occur. So wrapping it with try/ catch is a good idea.
try {
balance = (balance - Double.parseDouble(transaction1));//this will not work but the concept I need
lblSavingsBalance.setText(String.valueOf(balance));
} catch (NumberFormatException e) {
//Send error message like showing a toast
e.printStackTrace();
}

Related

Casting String to Integer not working, throwing NumberFormatException

The value of walletBalance is a string, eg "150.0".
I am trying to display an error message in form of a toast in another activity(SuccessActivity) is the amount to be withdrawn from the user is less than the wallet balance. I keep getting NumberFormatException error for the value of i, so i decided to use a try catch block but it still doesnt work. Here is the method below.
private void checkWalletBalance(int amount, Context context){
String walletBalance = Preferences.getBalance(context);
try {
int i = Integer.parseInt(walletBalance.trim());
if(amount < i){
Intent intent = new Intent(getBaseContext(), SuccessActivity.class);
startActivity(intent);
Toast. makeText(ActivityHome.this,"Insufficient Wallet Balance",Toast. LENGTH_LONG).show();
}
}
catch (NumberFormatException nfe){
System.out.println("NumberFormatException: " + nfe.getMessage());
}
}
Alos, I want to display a toast in the success Activity, If the condition i true. here is the code in success activity to display the toast message.
private void insufficientError(){
Intent intent = getIntent();
intent.getExtras();
Toast.makeText(SuccessActivity.this,"Insufficient Balance",Toast.LENGTH_LONG).show();
}
Like #Blackbelt commented, you are trying to parse a double string and not an integer.
Therefore, you need to do the following:
double amount = Double.parseDouble(walletBalance.trim());
You could use either of the following-
Double.valueOf(walletBalance.trim());
Double.parseDouble(walletBalance.trim());
And then if you want to convert them to Integer/int like this -
Integer i = Double.valueOf(walletBalance.trim()).intValue();
int i = (int) Double.parseDouble(walletBalance.trim());
NumberFormatException - Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.
Don't
int i = Integer.parseInt(walletBalance.trim()); //walletBalance.trim() ==150.0
Do
int i = (int) Double.parseDouble(walletBalance.trim());

Parse string to float/double [duplicate]

This question already has answers here:
How do I convert a String to Double in Java using a specific locale?
(8 answers)
Closed 3 years ago.
I am getting values from jTable and putting it in my DataBase (MySQL). In my DB table there is column PAYMENT that is double. When I try to put values from my jTable there is a problem with it:
String payment=(String) jTable1.getValueAt(row, 2);
double pay=double .parseDouble (payment);
........
pst.setDouble(3, zar);
I am getting this exception:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "84,21834324"
How can I put this column from jTable as double in my DB table?
P.S.: I tried with float too.
Replace your , with a .:
String payment = (String) jTable1.getValueAt(row, 2);
double pay = Double.parseDouble(payment.replace(",". "."));
........
pst.setDouble(3, zar);
Edit -- If you want to support more complex values:
import java.util.Locale;
import java.text.*;
class Main {
public static void main(String[] args) throws ParseException {
String v1 = "84,21834324";
String v2 = "1.234.567,89";
NumberFormat format = NumberFormat.getInstance(Locale.ENGLISH);
Number n1 = format.parse(v1);
Number n2 = format.parse(v2);
double d1 = n1.doubleValue();
double d2 = n2.doubleValue();
}
}
Lifted the edited solution from this question

Creating a Search Button (Double cannot converted to String)

private void searchProduct()
{
try {
Product p = new Product();
//Read data
p.setId(Double.parseDouble(textID.getText()));
//Display data
textDescription.setText(String.valueOf(p.getDescription()));
textPrice.setText(String.valueOf(p.getUnitPrice()));
textUOM.setText(String.valueOf(p.getUnitOfMeasurement()));
}
catch(NumberFormatException e)
{
JOptionPane.showMessageDialog(this.frame, "ID must be number", "Error",JOptionPane.ERROR_MESSAGE);
}
}
Hello recently I tried to put a button "Search" to find a product than equals to ID, but I don't know how to parse the ID than comes from the product class, I have a error.
Does the textID.getText() actually is a parseable double string? For instance "10.1" do but "10.1 " no.
Always I did this kind of conversion I use trim() to remove this extra white spaces as follow:
String stringValue = textID.getText();
if(stringValue != null) {
stringValue = stringValue.trim();
}
double doubleValue = Double.parseDouble(stringValue);
Se here http://docs.oracle.com/javase/8/docs/api/java/lang/Double.html#valueOf-java.lang.String- how to avoid NumberFormatException using a regular expression to text you string before try to convert it to double.

Java netbeans adding comma to the table

Hi i am new to this and i am locked in this problem, i am trying to figure out whether you can add a set of values (1,000 ....) to another value. Though i successfully linked an input that automatically changed into comma to the table in SQL, it seems that it cannot add two values that has that format, my client wants to see a comma in a table and when inputting values.
Can you guide me where to change my code, is there an automatic format of these in SQL? Or probably in the java code, I read some articles that you cannot do a comma format before adding as it is done after that.
Here is the code I added to automatically change the numbers into having a comma:
private void FaremoKeyReleased(java.awt.event.KeyEvent evt)
{
String a = Faremo.getText();
if (a.isEmpty())
{
a = "";
}
else
{
a = a.replace(",","");
a = NumberFormat.getNumberInstance(Locale.ENGLISH).format(Double.parseDouble(a));
a = a.replace(".", ",");
}
Faremo.setText(a);
}
My problem is i cannot add values linked to my SQL with that format.
[Sample data - http://i.stack.imgur.com/kVQII.png]
When i am getting the sum of it I am using these:
private void SumActionPerformed(java.awt.event.ActionEvent evt) {
try{
String sql = "Select sum(Faremo),sum(Eatery),sum(Admin),sum(Jisoo),sum(Cav1),sum(Cav2),sum(Reliance1),sum(Reliance2)from Dataa";
pst = conn.prepareStatement(sql);
rs=pst.executeQuery();
if(rs.next()){
String sum1 = rs.getString("sum(Faremo)");
SFaremo.setText(sum1);
String sum2 = rs.getString("sum(Eatery)");
SEatery.setText(sum2);
String sum3 = rs.getString("sum(Admin)");
SAdmin.setText(sum3);
String sum4 = rs.getString("sum(Jisoo)");
SJisoo.setText(sum4);
String sum5 = rs.getString("sum(Cav1)");
SCav1.setText(sum5);
String sum6 = rs.getString("sum(Cav2)");
SCav2.setText(sum6);
String sum7 = rs.getString("sum(Reliance1)");
SReliance1.setText(sum7);
String sum8 = rs.getString("sum(Reliance2)");
SReliance2.setText(sum8);
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}
Update_table();
}
Are the table columns where you want to save the numbers defined as float?
If you are sure that a value will only be a number make the table columns int. Depending on the kind of numbers, you can choose a variety of Data Types:
float, decimal,real.
These could all work. It is all depending on what the numbers represent.
If you are going to do math IN the cells, a double gives rounding problems (link).
For more info on Data Types check Data Types.

How do I calculate total hours in a GUI-based program?

I am creating a simple GUI-based time card. So I already have the implementation (given by a friend) but it was just made in a non-GUI program.
System.out.print("Enter time-in: ");
String strTimein = input.next();
String timeInArr[] = strTimein.split(":");
double dblTimeInHr = Double.parseDouble(timeInArr[0]);
double dblTimeInMin = Double.parseDouble(timeInArr[1]);
double dblTotalTimeIn = dblTimeInHr + (dblTimeInMin/60);
System.out.print("Enter time-out: ");
String strtimeout = input.next();
String timeOutArr[] = strtimeout.split(":");
double dblTimeOutHr = Double.parseDouble(timeOutArr[0]);
double dblTimeOutMin = Double.parseDouble(timeOutArr[1]);
double dblTotalTimeOut = dblTimeOutHr + (dblTimeOutMin/60);
totalHrs = totalHrs + (dblTotalTimeOut - dblTotalTimeIn);
It works actually. But I couldn't get it to work when I apply it now on my GUI-based program. So I have two JTextField, that is where the user will input the time-in and time-out. And another JTextField, total1, that is setEditable(false) where it will display the total hours.
total1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String timeIn = tIn1.getText();
String timeInArr[] = strtimein.split(":");
double dblTimeInHr = Double.parseDouble(timeInArr[0]);
double dblTimeInMin = Double.parseDouble(timeInArr[1]);
double dblTotalTimeIn = dblTimeInHr + (dblTimeInMin/60);
String timeOut = tOut1.getText();
String timeOutArr[] = strtimeout.split(":");
double dblTimeOutHr = Double.parseDouble(timeOutArr[0]);
double dblTimeOutMin = Double.parseDouble(timeOutArr[1]);
double dblTotalTimeOut = dblTimeOutHr + (dblTimeOutMin/60);
totalHours = totalHours + (dblTotalTimeOut - dblTotalTimeIn);
tal1.setText(totalHours);
}
});
The error I'm getting is "cannot find symbol" which points to:
String timeInArr[] = strTimein.split(":");
and
String timeOutArr[] = strTimeOut.split(":");
I know there's something wrong with my code, but I couldn't figure it out. Please help.
strtimein is not declared anywhere, you probably meant to use timeIn.
You have not declared those two strings in your code..
create these two strTimeOut and strTimeIn
Seems you actually wanted to use timeIn and timeOut
Well....
String timeIn = tIn1.getText();
String timeInArr[] = strtimein.split(":");
I guess you want to split the content of the textfield tIn1, so you should not use strtimein but timeIn. strtimein is not declared anywhere and that's what your error message says.
String timeInArr[] = timeIn.split(":");
The same goes for timeOut / strTimeOut below

Categories

Resources