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
Related
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();
}
This question already has answers here:
Problems using DecimalFormat
(6 answers)
Closed 2 years ago.
I am making a calculator app.
workingsTV is the place where calculating is shown.
resultsTV is the place showing the result of calculating.
workings is doing math by using rhino's library.
I want to add a comma at every three digits on both workingsTV and resultsTV.
I tried to use it like this for resultsTV.
DecimalFormat df = new DecimalFormat("###,###.####", new DecimalFormatSymbols(Locale.US));
result = Double.parseDouble(df.format(result));
But then the app was closed when to show result
This is the error message
Caused by: java.lang.reflect.InvocationTargetException
Caused by: java.lang.NumberFormatException: For input string: "1,235"
Here is the top part of the code
public class MainActivity extends AppCompatActivity {
TextView workingsTV;
TextView resultsTV;
String workings = "";
String CLEAR_INT_TEXT;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initTextView();
}
private void initTextView()
{
workingsTV = (TextView)findViewById(R.id.workingsTextView);
resultsTV = (TextView)findViewById(R.id.resultTextView);
}
private void setWorkings(String givenValue)
{
workings = workings + givenValue;
workingsTV.setText(workings);
}
public void equalsOnClick(View view)
{
Double result = null;
ScriptEngine engine = new ScriptEngineManager().getEngineByName("rhino");
try {
result = (Double) engine.eval(workings);
if (result != null)
{
DecimalFormat df = new DecimalFormat("###,###.####", new DecimalFormatSymbols(Locale.US));
result = Double.parseDouble(df.format(result));
int intVal = (int) result.doubleValue();
if (result == intVal)
{//Check if it's value is equal to its integer part
resultsTV.setText(String.valueOf(intVal));
}
else
{
resultsTV.setText(String.valueOf(result));
}
}
}
I'm using that function to convert double to formatted string
public String formatDouble(double value, int digits) {
DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols();
decimalFormatSymbols.setGroupingSeparator(',');
decimalFormatSymbols.setDecimalSeparator('.');
DecimalFormat decimalFormat = new DecimalFormat("###,##0.00", decimalFormatSymbols);
decimalFormat.setMinimumFractionDigits(digits);
decimalFormat.setMaximumFractionDigits(digits);
return decimalFormat.format(value);
}
In your code, you already have an result value here result = (Double) engine.eval(workings);. Why do you want get it second time? In addition, using formatted string, who may contains illegal character for double (comma char).
Just remove that two lines
DecimalFormat df = new DecimalFormat("###,###.####", new DecimalFormatSymbols(Locale.US));
result = Double.parseDouble(df.format(result));
And format result value when you'll set it to TextView, example with my function:
resultsTV.setText(formatDouble(result, 4));
At the end of equalsOnClick() method, you should set result or intVal to the workings variable to make it ready for next operations.
workings = String.valueOf(result);
Try this:
import java.text.NumberFormat;
import java.util.Locale;
Locale locale = new Locale("en", "US");
NumberFormat fmt = NumberFormat.getCurrencyInstance();
System.out.println(fmt.format(1235.00));
This question already has answers here:
Reading a plain text file in Java
(31 answers)
Closed 6 years ago.
i'm working on my project in JAVA and i have .txt file that contain data like this :
3.4413 44.5444 22.793
33.3321 222.1333 44.7785
23.3001 31.1333 4.7785
77.9999 8.0001 -1.3213 3.2311
so how can i read the .txt file and convert it to :
double[0][0] = {3.4413,44.5444,22.793}
double[0][1] = {33.3321 222.1333 44.7785}
double[1][0] = {23.3001 31.1333 4.7785}
double[1][1] = {77.9999 8.0001 -1.3213 3.2311}
If you are sure that you'll be getting only 3 entities in every line then you can do something like this:
public static void main (String[] args)
{
double[][] arr = new double[10][3];
int ptr = 0;
Scanner in = new Scanner(System.in);
while(in.hasNext()) {
arr[ptr][0] = in.nextDouble();
arr[ptr][1] = in.hasNext() ? in.nextDouble() : 0d;
arr[ptr++][2] = in.hasNext() ? in.nextDouble() : 0d;
}
}
Please note that here I have used Scanner and am taking input from System.in. You can replace it to take input from your file.
Considering the above input this will result in the following output:
arr[0][0] -> 3.4413
arr[0][1] -> 44.5444
arr[0][2] -> 22.793
For the first row and so on.
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.
i try to save my String value (50000000) into Double format, while I'm trying to show it again in my Edittext, I can't to show it in normal format, and it show as (5E+07), is there any way to convert from double format into String format?
I have try this way :
Double value_doble = 5E+07;
EditText.setText(String.valueOf(value_doble);
but its Still show as 5E+07, so my question how to convert from Double to String?
You can try this:
System.out.println(new BigDecimal(value_doble).toString());
Is this what you are looking for?
public static void main(String[] args) {
Double value_doble = 5E+07;
NumberFormat formatter = new DecimalFormat("###.#####");
String f = formatter.format(value_doble);
System.out.println(f);
}
I agree that you need use Formater
http://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html
but the pattern should be look like this:
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class DoubleFormat {
public static void main(String[] args) {
double valueD = 5E+07;
NumberFormat format = new DecimalFormat("#");
System.out.println(format.format(valueD));
}
}